﻿// DllImport
using Module_Debug.Others;
using Module_Debug.VDDIC_Gamma;
using System;
using System.Collections;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Module_Debug.MainForm;

namespace Module_Debug
{
    public partial class frmMain : Form
    {
        private Flash_gen frm_flash = null;
        private void flash_gen_click(object sender, EventArgs e)
        {
            if (frm_flash == null || frm_flash.IsDisposed)
            {
                frm_flash = new Flash_gen(this);//如果之前不存在，则new一个。
                frm_flash.Show();
            }
            else
            {
                frm_flash.Show();
            }
        }
                
        private void ForChenfenguiadj() //界面尺寸调整
        {
            if (changeUIflag)//恢复DDICDriver代码大窗口
            {
                btnDDicDriverDownload.Visible = false;
                rdo_HS.Visible = false;
                rdo_LP.Visible = false;
                btnPreProcessSourcecode.Visible = false;
                progressBar_DDIC.Visible = false;
                btnAddSourcecode.Visible = false;
                btnGetSourcecode.Visible = false;
                txtSourcecode.Visible = false;
                //btnRun.Visible = false;
                rdoOneLineSend.Visible = false;
                //btnIcAdj.Visible = false;
                lstMIPIDriver.Size = new System.Drawing.Size(494, 304);
                txtMIPIDriver.Size = new System.Drawing.Size(494, 26);
                // chkPoltWhite.Text = "上电刷白";
                changeUIflag = !changeUIflag;
            }
            else
            {
                btnDDicDriverDownload.Visible = true;
                rdo_HS.Visible = true;
                rdo_LP.Visible = true;
                rdoOneLineSend.Visible = true;
                btnPreProcessSourcecode.Visible = true;
                progressBar_DDIC.Visible = true;
                btnAddSourcecode.Visible = true;
                btnGetSourcecode.Visible = true;
                txtSourcecode.Visible = true;
                //btnRun.Visible = true;
                //btnIcAdj.Visible = true;
                lstMIPIDriver.Size = new System.Drawing.Size(277, 324);
                txtMIPIDriver.Size = new System.Drawing.Size(277, 26);
                // chkPoltWhite.Text = "刷白";
                changeUIflag = !changeUIflag;
            }

        }
        private void chkPoltWhite_CheckedChanged(object sender, EventArgs e)
        {
            if (chkPoltWhite.Checked == true)
            {
                chkPoltWhite.Text = "上电刷白";
                chkPoltBMP.Checked = false;
            }
            else
            {
                chkPoltWhite.Text = "上电刷黑";
            }
        }
        private void JDFJ_Show_to_Custom(out double Compress_gray)
        {
            //计算前级亮度
            if (HFZ_M_G.Value < 128 && Gen_BC_Bar.Value > 0)
            {
                double JDFJ_LAST_LUM;
                //450*（DBV/2047）^1.9
                JDFJ_LAST_LUM = (double)JDFJ_LUM.Value * Math.Pow((Gen_BC_Bar.Value / (double)(JDFJ_DBV.Value)), 1.9);
                //计算当前亮度
                double JDFJ_NOW_LUM;
                JDFJ_NOW_LUM = (double)JDFJ_LAST_LUM * Math.Pow(((double)(HFZ_M_G.Value) / 255), 2.2);
                //计算补偿灰阶
                Compress_gray = JDFJ_NOW_LUM < 1.5 ? ((double)(0.1267) * (Math.Pow(JDFJ_NOW_LUM, -0.3101)) + 0.9144) : 1;
            }
            else
            {
                Compress_gray = 1;
            }
        }
        private byte[] GetCRCArray_9f_A(byte[] arr, Byte speedflag)   //处理命令数组，在其头尾增加包头(9F,在一个包内包含多行code)以及CRC校验值，处理后的数据可以直接发送至下位机
        {
            string code_log = null;//可以用于将sendbuf转化为log，确认下发代码是否正确
            for (int i = 0; i < arr.Length;)
            {
                code_log = null;

                for (int j = 1; j < arr[i] + 1; j++)
                {
                    if (j == 1)
                    {
                        code_log = arr[j + i].ToString("X2");
                    }
                    else
                    {
                        code_log = code_log + "," + arr[j + i].ToString("X2");
                    }
                }
                showmsg(code_log, 5);
                i = i + arr[i] + 1;
            }


            CRC16 CRCData = new CRC16();//根据黑窗（99）黄窗（9f）手动测试写gamma结果，选择适当的gammacode打包下发方式  需要修改
            int arrNumbuer;                                                                                                                                                                                                                                                                                                                                             //51
            arrNumbuer = arr.Length;
            arrNumbuer += 6;
            byte[] Send_Datax = new byte[arrNumbuer];
            Send_Datax[0] = 0x9f;//格式：9f,speedflag(高低速),有效数据长度+1,一行code长度，一行code内容（多个Byte），一行code长度，一行code内容。。。，0xFF(结束标志位),crc1,crc2。
            Send_Datax[1] = (byte)(speedflag << 4);
            Send_Datax[2] = Convert.ToByte(arr.Length + 1);  //为兼容下位机命令，此位置填待传输有效数据长度+1 

            Send_Datax[arr.Length + 3] = 0xFF;  //添加结束标志位
            arr.CopyTo(Send_Datax, 3);//合并数组头 4个Byte 标志位
            //计算校验码                                                 
            CRCData.CalculateCrc16(Send_Datax, out Send_Datax[arrNumbuer - 2], out Send_Datax[arrNumbuer - 1]);
            return Send_Datax;
        }

        private void Gen_BC_Bar_Scroll(object sender, EventArgs e)
        {
            int bits_51h = Convert.ToInt16(Math.Pow(2, Convert.ToByte(Gen_51h_Bits.Text))) - 1;
            int bits_51h_copy = Convert.ToInt16(Gen_51h_Copy_Bits.Text);
            Gen_BC_Bar.Maximum = bits_51h;
            byte[] TepArr;
            byte DBV_HIGH = 0;
            byte DBV_LOW = 0;

            Value51index = Gen_BC_Bar.Value;

            if (IC_comboBox.SelectedIndex == Setting.IC_Type.HI3288) { Gen_BC_Bar.Maximum = bits_51h - 1; }
            try
            {
                if (bits_51h < 0x100)
                {
                    Gen_BC_lab.Text = "";
                    for (int co = 0; co < bits_51h_copy; co++)
                    {
                        Gen_BC_lab.Text = Gen_BC_lab.Text + "" + Gen_BC_Bar.Value.ToString("x2");
                    }
                }
                else
                {
                    if ((IC_comboBox.SelectedIndex == Setting.IC_Type.HI3288) && (!checkBoxfan.Checked))
                    {
                        //checkBoxfan.Checked = true;
                        //Gen_51h_Bits.Text = 14 + "";
                    }
                    if (checkBoxfan.Checked)   //IC里面的51值高低位换位输出
                    {
                        int tep51Value = Gen_BC_Bar.Value;
                        if ((IC_comboBox.SelectedIndex == Setting.IC_Type.HI3288))
                        {
                            //tep51Value += 0x8000;  //MSB为51 使能位
                        }
                        Gen_BC_lab.Text = "";
                        for (int co = 0; co < bits_51h_copy; co++)
                        {
                            Gen_BC_lab.Text = Gen_BC_lab.Text + "" + tep51Value.ToString("x4").Substring(2, 2) + "," + tep51Value.ToString("x4").Substring(0, 2);
                        }
                    }
                    else
                    {
                        Gen_BC_lab.Text = "";
                        for (int co = 0; co < bits_51h_copy; co++)
                        {
                            Gen_BC_lab.Text = Gen_BC_lab.Text + "" + Gen_BC_Bar.Value.ToString("x4").Substring(0, 2) + "," + Gen_BC_Bar.Value.ToString("x4").Substring(2, 2);
                        }
                    }
                    if (IC_comboBox.SelectedIndex == Setting.IC_Type.NT71181)
                    {
                        DBV_HIGH = Convert.ToByte(Convert.ToInt16(Gen_BC_Bar.Value) >> 8);
                        DBV_LOW = Convert.ToByte(Convert.ToInt16(Gen_BC_Bar.Value) & 0xFF);
                        TepArr = new byte[] {
                        4,0xC0, 0x06, 0x69, DBV_HIGH,
                        4,0xC0, 0x06, 0x6A, DBV_LOW,
                        };
                        frmMain.frmain.comPort.Write(GetCRCArray_9f_A(TepArr, 4), 0, TepArr.Length + 6);//使用直接用9f的方式发gamma
                    }
                }
                Generate_File_Click(Gen_DBC_control, null);
                if (CBX_JDFJ_TEST.Checked == true)
                {
                    double press_gray = 0.0;
                    double nue_gray = 0.0;
                    JDFJ_Show_to_Custom(out press_gray);
                    nue_gray = (double)(HFZ_M_G.Value) * press_gray;
                    HFZ_L_R.Value = (decimal)(Math.Round(nue_gray));
                    HFZ_L_G.Value = (decimal)(Math.Round(nue_gray));
                    HFZ_L_B.Value = (decimal)(Math.Round(nue_gray));
                    OLED_Show_Click(btnlogic_go, null);
                }
            }
            catch
            {
                MessageBox.Show("位深不支持！");
            }
        }
        private void XX1_ValueChanged(object sender, EventArgs e)
        {
            XX_VALUE.Text = (XX1.Value - XX0.Value).ToString();
            YY_VALUE.Text = (YY1.Value - YY0.Value).ToString();
        }

        private void Load_GammmPic(string filenames)
        {
            Int32 HACT_True = 0;
            Int32 HACT_Skip = 0;
            Int32 VACT_True = 0;
            Int32 m_txlen = 0;
            Int32 j = 0;
            FileStream aFile;

            //byte[] TemFileContent = new byte[1024 * 100];
            byte[] TemFileContent = new byte[512 * 4000 + 100];
            System.Int32 ByteReaded = 0x00;
            string FileName = "";
            Int32 BMoffset;
            if (chkDSCmode.Checked)
            {
                byte tep;
                FileName = Gamma_loading_path.Text + '\\' + filenames + ".dsc";
                aFile = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                ByteReaded = aFile.Read(TemFileContent, 0, 54);
                //if ((TemFileContent[0] == 0x44) && (TemFileContent[1] == 0x53) && (TemFileContent[2] == 0x43))
                { //此時dui'ying DSC 压缩图片
                    BMoffset = 132;
                    HACT_True = ((TemFileContent[12]) << 8) + TemFileContent[13];
                    VACT_True = ((TemFileContent[10] << 8) + TemFileContent[11]);
                    HACT_True /= 3;
                }
                //if ((Dis_mode.SelectedIndex == 1) && (Pixel_Offset_Enable.Checked == true)) //video
                //{
                //    HACT_Skip = HACT_True % 10 > 0 ? (HACT_True + 10 - HACT_True % 10) : HACT_True;
                //}
                //else
                {
                    HACT_Skip = HACT_True;
                }
                try
                { //5a a5 9DF0731A-----提前下个标志位告诉下位机开始送图了，避免特殊图片格式导致错误配置
                    TemFileContent[0] = 0xbd; TemFileContent[1] = 0x5a; TemFileContent[2] = 0xa5; TemFileContent[3] = 0x9d; TemFileContent[4] = 0xf0;
                    comPort.Write(TemFileContent, 0, 5);
                }
                catch
                {
                    show_LOG_main_msg("串口有误，请检查", "错误");
                    return;
                }
                //-----------------------------------
                try
                {
                    j = 0;
                    while (j < VACT_True)
                    {
                        if (HACT_True % 4 != 0)
                            aFile.Seek((j) * (HACT_True * 3 + (HACT_True % 4)) + BMoffset, SeekOrigin.Begin);
                        else
                            aFile.Seek((j) * HACT_True * 3 + BMoffset, SeekOrigin.Begin);

                        ByteReaded = aFile.Read(TemFileContent, 0, HACT_True * 3); // 
                        for (int m = 0; m < HACT_True * 3; m += 3)
                        {
                            tep = TemFileContent[m];
                            TemFileContent[m] = TemFileContent[m + 2];
                            TemFileContent[m + 2] = tep;   //R/G/B交换
                        }
                        try
                        {
                            comPort.Write(TemFileContent, 0, HACT_Skip * 3);
                        }
                        catch
                        {
                            show_LOG_main_msg("串口有误，请检查", "错误");
                            break;
                        }
                        m_txlen += ByteReaded;
                        progressBar1.Value = Convert.ToInt32((double)m_txlen / aFile.Length * 100);
                        label14.Text = progressBar1.Value.ToString() + "%";
                        Application.DoEvents();//重点，必须加上，否则父子窗体都假死
                        j++;

                    }
                    aFile.Close();
                }
                catch
                {
                    textBox1.Text += "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "送图异常";
                    textBox1.Select(textBox1.Text.Length, 0);
                    textBox1.ScrollToCaret();
                }
                try
                {
                    TemFileContent[0] = 0x5A; comPort.Write(TemFileContent, 0, 1);
                }
                catch
                {
                    show_LOG_main_msg("串口有误，请检查", "错误");
                    return;
                }
            }
            else
            {
                FileName = Gamma_loading_path.Text + '\\' + filenames + ".bmp";
                aFile = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                ByteReaded = aFile.Read(TemFileContent, 0, 54);
                BMoffset = ((TemFileContent[13] << 24) + (TemFileContent[12] << 16) + (TemFileContent[11] << 8) + TemFileContent[10]);
                HACT_True = ((TemFileContent[19]) << 8) + TemFileContent[18];
                VACT_True = ((TemFileContent[23] << 8) + TemFileContent[22]);

                HACT_Skip = HACT_True;
                try
                { //5a a5 9DF0731A-----提前下个标志位告诉下位机开始送图了，避免特殊图片格式导致错误配置
                    TemFileContent[0] = 0xbd; TemFileContent[1] = 0x5a; TemFileContent[2] = 0xa5; TemFileContent[3] = 0x9d; TemFileContent[4] = 0xf0;
                    comPort.Write(TemFileContent, 0, 5);
                }
                catch
                {
                    show_LOG_main_msg("串口有误，请检查", "错误");
                    return;
                }
                //-----------------------------------
                try
                {
                    j = 1;
                    while (j <= VACT_True)
                    {
                        if (HACT_True % 4 != 0)
                            aFile.Seek((VACT_True - j) * (HACT_True * 3 + (HACT_True % 4)) + BMoffset, SeekOrigin.Begin);
                        else
                            aFile.Seek((VACT_True - j) * HACT_True * 3 + BMoffset, SeekOrigin.Begin);

                        ByteReaded = aFile.Read(TemFileContent, 0, HACT_True * 3); // 
                        try
                        {
                            comPort.Write(TemFileContent, 0, HACT_Skip * 3);
                        }
                        catch
                        {
                            show_LOG_main_msg("串口有误，请检查", "错误");
                            break;
                        }
                        m_txlen += ByteReaded;
                        j++;
                    }
                    aFile.Close();
                    TemFileContent[0] = 0x5A;
                    try
                    {
                        comPort.Write(TemFileContent, 0, 1);
                    }
                    catch
                    {
                        show_LOG_main_msg("串口有误，请检查", "错误");
                        return;
                    }
                }
                catch
                {
                    textBox1.Text += "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "啥图片都没显示";
                    textBox1.Select(textBox1.Text.Length, 0);
                    textBox1.ScrollToCaret();
                }
            }
        }
        public void CAS200_Measure_Information(double Dgv_lum, double Dgv_x, double Dgv_y, double Dgv_flicker)
        {
            int Row_Accum = 0, Current_Index = 0, Row_flag = 0;

            DataGridViewRow Row1 = new DataGridViewRow();
            Row_Accum = this.CAS200_dataGridView.Rows.Count - 1;
            if (Row_Accum != 0)
            {
                Current_Index = this.CAS200_dataGridView.SelectedCells[0].RowIndex;
                if ((Current_Index != Row_Accum - 1) && (Current_Index != Row_Accum))
                {
                    Row_Accum = Current_Index;
                    Row_flag = 1;
                }
                else
                {
                    this.CAS200_dataGridView.Rows.Add(Row1);
                }
                if ((Row_Accum != 0) && (Row_flag != 1))
                {
                    if (Current_Index != Row_Accum)
                    {
                        this.CAS200_dataGridView.Rows[Row_Accum - 1].Selected = false;
                        this.CAS200_dataGridView.Rows[Row_Accum].Selected = true;
                    }
                }
            }
            else
            {
                this.CAS200_dataGridView.Rows.Add(Row1);
            }

            if (cbx_follow_csv.Checked == true)
            {
                this.CAS200_dataGridView.Rows[Row_Accum].Cells[0].Value = IRC_picname_list[IRC_images_counts];//序号
            }
            else
            {
                this.CAS200_dataGridView.Rows[Row_Accum].Cells[0].Value = Row_Accum + 1;//序号
            }
            //Rows[x]为第x行,Cells[x]为第x列
            if (cbo_CASDK_MODE.SelectedIndex == 0) //Lvxy
            {
                this.CAS200_dataGridView.Rows[Row_Accum].Cells[1].Value = Dgv_x.ToString("#0.0000");
                this.CAS200_dataGridView.Rows[Row_Accum].Cells[2].Value = Dgv_y.ToString("#0.0000");
                this.CAS200_dataGridView.Rows[Row_Accum].Cells[3].Value = Dgv_lum.ToString("#0.0000");
            }
            else if (cbo_CASDK_MODE.SelectedIndex == 1) //JEITA Flicker
            {
                this.CAS200_dataGridView.Rows[Row_Accum].Cells[4].Value = Dgv_flicker.ToString("#0.0000");
            }

            if (PMU_power_print_in_Box_Enable.Checked == true || PMU_power_print_in_GradView_Enable.Checked == true)
            {
                this.CAS200_dataGridView.Rows[Row_Accum].Cells[5].Value = VCI.ToString("0.00");
                this.CAS200_dataGridView.Rows[Row_Accum].Cells[6].Value = VCIC.ToString("0.00");
                this.CAS200_dataGridView.Rows[Row_Accum].Cells[7].Value = VDDIO.ToString("0.00");
                this.CAS200_dataGridView.Rows[Row_Accum].Cells[8].Value = VDDIOC.ToString("0.00");
                this.CAS200_dataGridView.Rows[Row_Accum].Cells[9].Value = AVDD.ToString("0.00");
                this.CAS200_dataGridView.Rows[Row_Accum].Cells[10].Value = AVDDC.ToString("0.00");
                this.CAS200_dataGridView.Rows[Row_Accum].Cells[11].Value = ELVSS.ToString("0.00");
                this.CAS200_dataGridView.Rows[Row_Accum].Cells[12].Value = ELVSSC.ToString("0.00");
                this.CAS200_dataGridView.Rows[Row_Accum].Cells[13].Value = ELVDD.ToString("0.00");
                this.CAS200_dataGridView.Rows[Row_Accum].Cells[14].Value = ELVDDC.ToString("0.00");
                this.CAS200_dataGridView.Rows[Row_Accum].Cells[15].Value = VBAT.ToString("0.00");
                this.CAS200_dataGridView.Rows[Row_Accum].Cells[16].Value = VBATC.ToString("0.00");
                this.CAS200_dataGridView.Rows[Row_Accum].Cells[17].Value = DVDD.ToString("0.00");
                this.CAS200_dataGridView.Rows[Row_Accum].Cells[18].Value = DVDDC.ToString("0.00");
            }

            if (Row_flag == 1)
            {
                Row_flag = 0;
                Row_Accum = this.CAS200_dataGridView.Rows.Count - 1;
                this.CAS200_dataGridView.Rows[Current_Index].Selected = false;
                this.CAS200_dataGridView.Rows[Row_Accum - 1].Selected = true;
            }
            CAS200_dataGridView.FirstDisplayedScrollingRowIndex = CAS200_dataGridView.RowCount - 1;
        }
        bool ContinuousLvTestFlag = false; //  连续测量标志位
        private int cbx_follow_text_length_index = 0;
        private int cbx_follow_text_length = 0;
        private string cbx_follow_csv_defaultfilePath = "";
        private ArrayList IRC_picname_list = new ArrayList();
        private string IRC_foldpath;
        private int IRC_ListBox_Index = 0;
        private int IRC_images_counts = 0;
        private bool IRC_Switch_file_flag = false;
        private int IRC_Measure_Count = 0;

        bool Ca4x00calFlag = false;
        int flicker_first_init = 0;   //0:defualt 1：410 连上0cal  2：410连上测flicker  0cal 3：测量flicker
        private Flicker flicker=new Flicker();
        double fli = 0, fr = 0, lv = 0, xx = 0, yy = 0;
        int pattern_index = 0;
        private void btn_CAS200_Synt_Click(object sender, EventArgs e)
        {

            Button btnTmp = (Button)sender;
            Application.DoEvents();
            switch (btnTmp.Name)
            {
                case "btn_CAS200_Measure":
                    {
                        //CASDK_AutoMeasure_flag = 0;
                        if (!Ca4x00calFlag) { show_LOG_main_msg("检查CAx10是否连接/0Cal", "注意"); return; }
                        btn_CASDK_Measure.Text = "测量";
                        btn_CASDK_Measure.BackColor = Color.Green;
                        Msr_CASDK(); Msr_CASDK(); Msr_CASDK();
                        CAS200_Measure_Information(CASDK_LUM, CASDK_x, CASDK_y, CASDK_JEITA_Flicker);
                    }
                    break;
                case "btn_CAS200_Measure_Lxy_and_Power":
                    {
                        //CASDK_AutoMeasure_flag = 0;
                        if (!Ca4x00calFlag) { show_LOG_main_msg("检查CAx10是否连接/0Cal", "注意"); return; }
                        btn_CASDK_Measure.Text = "测量";
                        btn_CASDK_Measure.BackColor = Color.Green;

                        PMU_power_print_in_Box_Enable.Checked = true;
                        PMU_OPERATION_Click(btnPowertest, null);
                        Thread.Sleep(150);
                        Application.DoEvents();
                        Msr_CASDK();
                        CAS200_Measure_Information(CASDK_LUM, CASDK_x, CASDK_y, CASDK_JEITA_Flicker);
                        PMU_power_print_in_Box_Enable.Checked = false;
                    }
                    break;
                case "btn_CAS200Save":
                    {
                        SaveFileDialog sf = new SaveFileDialog(); //对话框
                        sf.Filter = @"csv文件(*.csv)|*.csv|所有文件(*.*)|*.*"; //定义保存的文件的类型

                        string str = "序号,x坐标,y坐标,亮度\r\n";
                        if (PMU_power_print_in_Box_Enable.Checked == true)
                        {
                            str = "序号,x坐标,y坐标,亮度,VCI电压,VCI电流," +
                                "VDDI电压,VDDI电流,AVDD电压,AVDD电流," +
                                "ELVSS电压,ELVSS电流,ELVDD电压,ELVDD电流," +
                                "VBAT电压,VBAT电流,DVDD电压,DVDD电流" + "\r\n";
                        }

                        if (cbx_follow_csv_auto_save.Checked == true)
                        {
                            sf.InitialDirectory = IRC_foldpath;
                        }
                        if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
                        {
                            if (sf.FileName == "") return; //如果没有输入文件名
                            try
                            {
                                StreamWriter sw = null; //文件流
                                sw = new StreamWriter(sf.FileName, false, Encoding.UTF8);
                                if (cbx_follow_gamma_points_MSB_LSB.Checked == false)
                                {
                                    for (int i = 0; i < (this.CAS200_dataGridView.Rows.Count - 1); i++)
                                    {
                                        str = str + this.CAS200_dataGridView.Rows[i].Cells[0].Value.ToString() + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[1].Value.ToString() + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[2].Value.ToString() + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[3].Value.ToString();

                                        if (cbo_CASDK_MODE.SelectedIndex == 1)
                                        {
                                            str = str + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[4].Value.ToString();
                                        }

                                        if (PMU_power_print_in_Box_Enable.Checked == true || PMU_power_print_in_GradView_Enable.Checked == true)
                                        {
                                            str = str + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[5].Value.ToString() + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[6].Value.ToString() + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[7].Value.ToString() + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[8].Value.ToString() + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[9].Value.ToString() + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[10].Value.ToString() + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[11].Value.ToString() + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[12].Value.ToString() + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[13].Value.ToString() + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[14].Value.ToString() + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[15].Value.ToString() + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[16].Value.ToString() + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[17].Value.ToString() + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[18].Value.ToString() + "\r\n";
                                        }
                                        else
                                        {
                                            str = str + "\r\n";
                                        }
                                    }
                                }
                                else
                                {
                                    for (int i = this.CAS200_dataGridView.Rows.Count - 2; i >= 0; i--)
                                    {
                                        str = str + this.CAS200_dataGridView.Rows[this.CAS200_dataGridView.Rows.Count - 2 - i].Cells[0].Value.ToString() + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[1].Value.ToString() + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[2].Value.ToString() + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[3].Value.ToString();

                                        if (cbo_CASDK_MODE.SelectedIndex == 1)
                                        {
                                            str = str + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[4].Value.ToString();
                                        }

                                        if (PMU_power_print_in_Box_Enable.Checked == true || PMU_power_print_in_GradView_Enable.Checked == true)
                                        {
                                            str = str + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[5].Value.ToString() + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[6].Value.ToString() + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[7].Value.ToString() + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[8].Value.ToString() + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[9].Value.ToString() + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[10].Value.ToString() + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[11].Value.ToString() + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[12].Value.ToString() + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[13].Value.ToString() + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[14].Value.ToString() + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[15].Value.ToString() + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[16].Value.ToString() + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[17].Value.ToString() + ","
                                            + this.CAS200_dataGridView.Rows[i].Cells[18].Value.ToString() + "\r\n";
                                        }
                                        else
                                        {
                                            str = str + "\r\n";
                                        }
                                    }
                                }

                                sw.WriteLine(str);
                                sw.Dispose(); //释放资源
                                sw.Close(); //关闭数据流
                                show_LOG_main_msg("测试数据保存OK！", "系统提示：");
                            }
                            catch
                            {
                                show_LOG_main_msg("测试数据保存时发生错误，请再试！", "系统提示：");
                            }
                        }
                    }
                    break;
                case "btn_CAS200_load":
                    {
                        OpenFileDialog sf = new OpenFileDialog();
                        int Line_Count = 0;
                        string strtmp = "";
                        sf.Filter = @"csv文件(*.csv)|*.csv|所有文件(*.*)|*.*"; //定义文件的类型
                        sf.Title = "数据导入";
                        if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
                        {
                            FileStream fs = new FileStream(sf.FileName, FileMode.Open, FileAccess.Read);
                            StreamReader streamReader = new StreamReader(fs, Encoding.GetEncoding("GBK"));
                            streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
                            string strLine = streamReader.ReadLine();
                            while (!string.IsNullOrEmpty(strLine))
                            {
                                strtmp = strtmp + strLine + ",";
                                strLine = streamReader.ReadLine(); //循环读取下一行
                                Line_Count++;
                            }
                            fs.Close(); //关闭流
                            streamReader.Close();
                            string[] arrtmp = strtmp.Split(new Char[] { ',' });
                            for (int j = 1; j < Line_Count - 1; j++)
                            {
                                DataGridViewRow Row1 = new DataGridViewRow();
                                CAS200_dataGridView.Rows.Add(Row1);
                            }
                            try
                            {
                                for (int i = 0; i < Line_Count - 1; i++)//有一行标题
                                {
                                    CAS200_dataGridView.Rows[i].Cells[0].Value = arrtmp[4 * (i + 1) + 0];
                                    CAS200_dataGridView.Rows[i].Cells[1].Value = arrtmp[4 * (i + 1) + 1];
                                    CAS200_dataGridView.Rows[i].Cells[2].Value = arrtmp[4 * (i + 1) + 2];
                                    CAS200_dataGridView.Rows[i].Cells[3].Value = arrtmp[4 * (i + 1) + 3];
                                    CAS200_dataGridView.Rows[i].Cells[4].Value = arrtmp[4 * (i + 1) + 4];

                                    if (PMU_power_print_in_Box_Enable.Checked == true || PMU_power_print_in_GradView_Enable.Checked == true)
                                    {
                                        CAS200_dataGridView.Rows[i].Cells[5].Value = arrtmp[4 * (i + 1) + 5];
                                        CAS200_dataGridView.Rows[i].Cells[6].Value = arrtmp[4 * (i + 1) + 6];
                                        CAS200_dataGridView.Rows[i].Cells[7].Value = arrtmp[4 * (i + 1) + 7];
                                        CAS200_dataGridView.Rows[i].Cells[8].Value = arrtmp[4 * (i + 1) + 8];
                                        CAS200_dataGridView.Rows[i].Cells[9].Value = arrtmp[4 * (i + 1) + 9];
                                        CAS200_dataGridView.Rows[i].Cells[10].Value = arrtmp[4 * (i + 1) + 10];
                                        CAS200_dataGridView.Rows[i].Cells[11].Value = arrtmp[4 * (i + 1) + 11];
                                        CAS200_dataGridView.Rows[i].Cells[12].Value = arrtmp[4 * (i + 1) + 12];
                                        CAS200_dataGridView.Rows[i].Cells[13].Value = arrtmp[4 * (i + 1) + 13];
                                        CAS200_dataGridView.Rows[i].Cells[14].Value = arrtmp[4 * (i + 1) + 14];
                                        CAS200_dataGridView.Rows[i].Cells[15].Value = arrtmp[4 * (i + 1) + 15];
                                        CAS200_dataGridView.Rows[i].Cells[16].Value = arrtmp[4 * (i + 1) + 16];
                                        CAS200_dataGridView.Rows[i].Cells[17].Value = arrtmp[4 * (i + 1) + 17];
                                        CAS200_dataGridView.Rows[i].Cells[18].Value = arrtmp[4 * (i + 1) + 18];
                                    }
                                }
                                show_LOG_main_msg("测试数据导入OK！", "提示：");
                            }
                            catch
                            {
                                show_LOG_main_msg("测试数据导入时发生错误！", "提示：");
                            }
                        }
                    }
                    break;
                case "btn_CAS200_Clean":
                    {
                        DialogResult dr = MessageBox.Show("确认清空列表数据吗？", "系统提示", MessageBoxButtons.OKCancel);
                        if (dr == DialogResult.OK)
                        {
                            this.CAS200_dataGridView.Rows.Clear();
                        }
                        else {; }
                    }
                    break;
                case "btn_CAS200_Delect":
                    {
                        int Current_Index, Row_Accum;
                        Current_Index = this.CAS200_dataGridView.SelectedCells[0].RowIndex;
                        DataGridViewRow Row1 = CAS200_dataGridView.Rows[Current_Index];
                        this.CAS200_dataGridView.Rows.Remove(Row1);
                        this.CAS200_dataGridView.Rows[Current_Index].Selected = false;
                        Row_Accum = this.CAS200_dataGridView.Rows.Count - 1;
                        for (Current_Index = 0; Current_Index < Row_Accum; Current_Index++)
                        {
                            this.CAS200_dataGridView.Rows[Current_Index].Cells[0].Value = Current_Index + 1;//序号
                        }
                        this.CAS200_dataGridView.Rows[Row_Accum - 1].Selected = true;
                        CAS200_dataGridView.FirstDisplayedScrollingRowIndex = CAS200_dataGridView.RowCount - 1;
                    }
                    break;
                case "btn_CAS200_Stop":
                    {
                        T3.Enabled = false;
                        T3.Stop();
                        ContinuousLvTestFlag = false;
                        pattern_index = 0;
                    }
                    break;
                case "btn_CAS200_Start":
                    {
                        if (!Ca4x00calFlag) { show_LOG_main_msg("检查CAx10是否连接/0Cal", "注意"); return; }
                        CAS200_Measure_Gray = Convert.ToInt32(text_51_start_bit.Text);
                        T3.Enabled = false;
                        if (cbx_follow_project_gamma_points.Checked == true)
                        {
                            cbx_follow_project_gamma_points_CheckedChanged(null, e);
                            if (rBt_Gamma_W.Checked == true)
                            {
                                checkBox1.Checked = false;
                                numPatternR.Value = numPatternG.Value = numPatternB.Value = Project_Gamma_Point[Project_Gamma_Point_Index];
                            }
                            else if (rBt_Gamma_R.Checked == true)
                            {
                                checkBox1.Checked = false;
                                numPatternR.Value = Project_Gamma_Point[Project_Gamma_Point_Index];
                                numPatternG.Value = 0;
                                numPatternB.Value = 0;
                            }
                            else if (rBt_Gamma_G.Checked == true)
                            {
                                checkBox1.Checked = false;
                                numPatternR.Value = 0;
                                numPatternG.Value = Project_Gamma_Point[Project_Gamma_Point_Index];
                                numPatternB.Value = 0;
                            }
                            else if (rBt_Gamma_B.Checked == true)
                            {
                                checkBox1.Checked = false;
                                numPatternR.Value = 0;
                                numPatternG.Value = 0;
                                numPatternB.Value = Project_Gamma_Point[Project_Gamma_Point_Index];
                            }

                            Application.DoEvents();
                            Pattern_Write((byte)(numPatternR.Value), (byte)(numPatternG.Value), (byte)(numPatternB.Value));
                            Thread.Sleep(100);
                        }
                        else if (cbx_follow_gamma_vesa_partial.Checked == true)
                        {
                            numPatternR.Value = numPatternG.Value = numPatternB.Value = 255;
                            try
                            {
                                Load_GammmPic(numPatternR.Value.ToString()); //Load pic
                            }
                            catch
                            {
                                MessageBox.Show("请正确指定图片路径并注意命名（255.bmp、254.bmp、253.bmp、...）！");
                            }
                        }
                        else if (cbx_follow_text.Checked == true)
                        {
                            IRC_Measure_Count = 0;
                            cbx_follow_text_length_index = 0;
                            string strLine = Convert.ToString(follow_context.Text);
                            string[] arr = strLine.Split('\n'); //以逗号分割，添加到数
                            cbx_follow_text_length = arr.Length;  //获取的行数
                        }
                        else if (cbx_follow_csv.Checked == true)
                        {
                            this.CAS200_dataGridView.Rows.Clear();
                            IRC_images_counts = 0;
                        }
                        ContinuousLvTestFlag = true;
                        T3.Enabled = true;
                        T3.Interval = int.Parse(CAS200_txt1.Text);//延时
                    }
                    break;
                case "btn_CASDK_Disconnect":
                    {
                        CASDK_Disconnect();
                    }
                    break;
                case "btn_CASDK_Measure":
                    {
                      
                        if (!Ca4x00calFlag) { show_LOG_main_msg("检查CAx10是否连接/0Cal", "注意"); return; }
                        if (cbo_CASDK_MODE.SelectedIndex==0)  //lvxy
                        { Msr_CASDK(); }
                        else if (cbo_CASDK_MODE.SelectedIndex == 1)  //flicker
                        {
                            
                            this.btn_CASDK_Measure.Enabled = false;
                             this.btn_CASDK_Measure.Text = "WAIT..";
                            flicker.get_flicker(ref fli,ref fr);
                            flicker.get_lvxy(ref xx,ref yy,ref lv );
                            this.lab_CASDK_Lv.Text = lv.ToString().Substring(0, 6);
                            this.lab_CASDK_Sx.Text = xx.ToString().Substring(0, 6);
                            this.lab_CASDK_Sy.Text = yy.ToString().Substring(0, 6);
                            this.flicker_label.Text = fli.ToString("F4");
                            this.fre_label.Text = fr.ToString("F4");
                            this.btn_CASDK_Measure.Enabled = true;
                            this.btn_CASDK_Measure.Text = "测量";


                        }
                       
                    }
                    break;
                case "Load_following_text":
                    {
                        OpenFileDialog ttsf = new OpenFileDialog();
                        int ttLine_Count = 0;
                        string tt_strtmp = "";
                        ttsf.Filter = @"txt文件(*.txt)|*.txt|所有文件(*.*)|*.*"; //定义文件的类型
                        ttsf.Title = "脚本导入";
                        if (ttsf.ShowDialog() == DialogResult.OK) //如果确定保存
                        {
                            FileStream ttfs = new FileStream(ttsf.FileName, FileMode.Open, FileAccess.Read);
                            StreamReader streamReader = new StreamReader(ttfs, Encoding.GetEncoding("GBK"));
                            streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
                            follow_context.Text = streamReader.ReadToEnd();
                            ttfs.Close(); //关闭流
                            streamReader.Close();
                        }
                    }
                    break;
                case "btn_load_gamma_patten":
                    {
                        if (txtPicAddr.Text != "")
                        {
                            defaultfilePath = txtPicAddr.Text;
                        }
                        else
                        {
                            StreamReader streamReader = new StreamReader("./update/Picaddr.txt", Encoding.Default);
                            defaultfilePath = streamReader.ReadLine();
                            streamReader.Close();
                        }
                        FolderBrowserDialog fldb = new FolderBrowserDialog();
                        if (defaultfilePath != "")
                        {
                            //设置此次默认目录为上一次选中目录
                            fldb.SelectedPath = defaultfilePath;
                        }
                        fldb.ShowNewFolderButton = false;
                        DialogResult res = fldb.ShowDialog();
                        if (res != System.Windows.Forms.DialogResult.OK)
                        {
                            MessageBox.Show("没选择任何文件夹.");
                            return;
                        }
                        Gamma_loading_path.Text = fldb.SelectedPath;

                        if (!Directory.Exists(Gamma_loading_path.Text))
                        {
                            MessageBox.Show("文件夹不存在.");
                            return;
                        }
                    }
                    break;
                case "btn_load_gamma_point":
                    {
                        OpenFileDialog ttsf = new OpenFileDialog();
                        int ttLine_Count = 0;
                        string tt_strtmp = "";
                        ttsf.Filter = @"txt文件(*.txt)|*.txt|所有文件(*.*)|*.*"; //定义文件的类型
                        ttsf.Title = "脚本导入";
                        if (ttsf.ShowDialog() == DialogResult.OK) //如果确定保存
                        {
                            FileStream ttfs = new FileStream(ttsf.FileName, FileMode.Open, FileAccess.Read);
                            StreamReader streamReader = new StreamReader(ttfs, Encoding.GetEncoding("GBK"));
                            streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
                            tBx_project_gamma_points_define.Text = streamReader.ReadToEnd();
                            ttfs.Close(); //关闭流
                            streamReader.Close();
                        }
                    }
                    break;
                case "btn_Load_following_csv":
                    {
                        FolderBrowserDialog fldb = new FolderBrowserDialog();
                        //首次defaultfilePath为空，按FolderBrowserDialog默认设置（即桌面）选择            
                        if (cbx_follow_csv_defaultfilePath != "")
                        {
                            //设置此次默认目录为上一次选中目录
                            fldb.SelectedPath = cbx_follow_csv_defaultfilePath;
                        }

                        fldb.ShowNewFolderButton = false;
                        DialogResult res = fldb.ShowDialog();
                        if (res != System.Windows.Forms.DialogResult.OK)
                        {
                            MessageBox.Show("没选择任何文件夹.");
                            return;
                        }
                        cbx_follow_csv_defaultfilePath = fldb.SelectedPath;
                        path = fldb.SelectedPath;
                        if (!Directory.Exists(path))
                        {
                            MessageBox.Show("文件夹不存在.");
                            return;
                        }
                        this.IRC_PIC_ListBox.Items.Clear();
                        IRC_ListBox_Index = 0;
                        var filePath = Directory.GetFiles(path, "*.csv", SearchOption.AllDirectories);
                        foreach (string ij in filePath)//遍历所有路径下的CSV，标定绝对路径
                        {
                            this.IRC_PIC_ListBox.Items.Add(ij);
                        }
                        if (IRC_PIC_ListBox.Items.Count > 0)
                        {
                            IRC_PIC_ListBox.SelectedIndex = 0;
                            IRC_Switch_file_flag = true;
                        }
                        else
                        {
                            MessageBox.Show("路径内未检索到CSV文件");
                            return;
                        }
                    }
                    break;
                default: break;
            }
        }
        private void CASDK_Disconnect()
        {
            if (CA_Sel.SelectedIndex == 1)
            {
                CaSDKObj.Disconnect();
            }
            else if (CA_Sel.SelectedIndex == 2)
            {
                CMadj.CMA01_Disconnect();
            }
            else if (CA_Sel.SelectedIndex == 3)
            {
                Eye402Obj.EYE2_402_Close();
            }
            btnCal_manual.Enabled = true;
        }
        private void T3_Tick(object sender, EventArgs e)
        {
            T3.Enabled = false;
            Application.DoEvents();
            Msr_CASDK(); Msr_CASDK();
            if (PMU_power_print_in_Box_Enable.Checked == true && cbx_follow_project_gamma_points.Checked == false && cbx_follow_csv.Checked == false)
            {
                Thread.Sleep(1000);
                PMU_OPERATION_Click(btnPowertest, null);
                Thread.Sleep(100);
            }
            if (cbx_follow_text.Checked == true)
            {
                try
                {
                    checkBox1.Checked = false;
                    if (follow_context.Text == string.Empty)
                    {
                        MessageBox.Show("内容为空!");
                    }
                    else
                    {
                        string perline = string.Empty;
                        string strLine = Convert.ToString(follow_context.Text);
                        string[] arr = strLine.Split('\n'); //以逗号分割，添加到数

                        perline = arr[cbx_follow_text_length_index];
                        perline = perline.Replace(" ", "");
                        perline = perline.Replace(";", "");
                        perline = perline.Replace("#", "/");
                        perline = perline.Replace("//", "/");
                        perline = perline.Replace("\r", "/");
                        perline = perline.Replace("\n", "/"); //单行整体处理.  

                        if (perline.Contains("/")) //去掉注解
                        {
                            perline = perline.Substring(0, perline.IndexOf("/"));
                        }
                        perline = perline.ToUpper();
                        if (perline.Contains("BACKCOLOR"))
                        {
                            perline = perline.Replace("BACKCOLOR", "");
                            string[] per_arr = perline.Split(','); //以逗号分割，添加到数组  
                            numPatternR.Value = Convert.ToByte(per_arr[0]);
                            numPatternG.Value = Convert.ToByte(per_arr[1]);
                            numPatternB.Value = Convert.ToByte(per_arr[2]);
                        }
                        else if (perline.Contains("LOCALCOLOR"))
                        {
                            perline = perline.Replace("LOCALCOLOR", "");
                            string[] per_arr = perline.Split(','); //以逗号分割，添加到数组  
                        }
                        else if (perline.Contains("SIZE"))
                        {
                            perline = perline.Replace("SIZE", "");
                            string[] per_arr = perline.Split(','); //以逗号分割，添加到数组  
                            XX0.Value = Convert.ToUInt16(per_arr[0]);
                            XX1.Value = Convert.ToUInt16(per_arr[1]);
                            YY0.Value = Convert.ToUInt16(per_arr[2]);
                            YY1.Value = Convert.ToUInt16(per_arr[3]);
                            OLED_Show_Click(btnlogic_pic, null);
                            Thread.Sleep(100);
                        }
                        else if (perline.Contains("DELAY"))
                        {
                            perline = perline.Replace("DELAY", "");
                            Thread.Sleep(Convert.ToInt32(perline));
                        }
                        else if (perline.Contains("COLOR"))
                        {
                            perline = perline.Replace("COLOR", "");
                            string[] per_arr = perline.Split(','); //以逗号分割，添加到数组  
                            numPatternR.Value = Convert.ToByte(per_arr[0]);
                            numPatternG.Value = Convert.ToByte(per_arr[1]);
                            numPatternB.Value = Convert.ToByte(per_arr[2]);
                            OLED_Show_Click(btnPatternW, null);
                            Thread.Sleep(100);
                        }
                        else if (perline.Contains("LOGIC"))
                        {
                            perline = perline.Replace("LOGIC", "");
                            cbx_logic_pic_index.SelectedIndex = Convert.ToInt32(perline);
                            Application.DoEvents();
                            OLED_Show_Click(btnlogic_pic, null);
                            Thread.Sleep(100);
                        }
                        else if (perline.Contains("BMP"))
                        {
                            perline = perline.Replace("BMP", "");
                            listBox3_BMPFile.SelectedIndex = Convert.ToInt32(perline);
                            Application.DoEvents();
                            btnPrevPic_Click(null, null);
                            Thread.Sleep(100);
                        }
                        else if (perline.Contains("REGW"))
                        {
                            perline = perline.Replace("REGW:", "");
                            Gen_BC_lab.Text = perline;
                            Generate_File_Click(Gen_DBC_control, null);
                            Thread.Sleep(50);
                        }
                        else if (perline.Contains("MEASURE"))
                        {
                            btn_CAS200_Synt_Click(btn_CAS200_Measure, null);
                            Thread.Sleep(50);
                            Application.DoEvents();
                        }
                        else if (perline.Contains("POWERTEST"))
                        {
                            PMU_power_print_in_Box_Enable.Checked = true;
                            Thread.Sleep(1000);
                            PMU_OPERATION_Click(btnPowertest, null);
                            Thread.Sleep(100);
                        }
                        else if (perline.Contains("RICKRATIO"))
                        {
                            perline = perline.Replace("RICKRATIO", "");
                            HFZ_Ratio.Value = Convert.ToInt32(perline);
                            Thread.Sleep(5);
                        }
                        else if (perline.Contains("RICKBC"))
                        {
                            perline = perline.Replace("RICKBC", "");
                            string[] per_arr = perline.Split(','); //以逗号分割，添加到数组  
                            HFZ_M_R.Value = Convert.ToByte(per_arr[0]);
                            HFZ_M_G.Value = Convert.ToByte(per_arr[1]);
                            HFZ_M_B.Value = Convert.ToByte(per_arr[2]);
                            OLED_Show_Click(btnlogic_go, null);
                            Thread.Sleep(5);
                        }
                        else if (perline.Contains("RICKLC"))
                        {
                            perline = perline.Replace("RICKLC", "");
                            string[] per_arr = perline.Split(','); //以逗号分割，添加到数组  
                            HFZ_L_R.Value = Convert.ToByte(per_arr[0]);
                            HFZ_L_G.Value = Convert.ToByte(per_arr[1]);
                            HFZ_L_B.Value = Convert.ToByte(per_arr[2]);
                            OLED_Show_Click(btnlogic_go, null);
                            Thread.Sleep(5);
                        }
                        else if (perline.Contains("RICKCXY"))
                        {
                            perline = perline.Replace("RICKCXY", "");
                            string[] per_arr = perline.Split(','); //以逗号分割，添加到数组  
                            HFZ_CX.Value = Convert.ToByte(per_arr[0]);
                            HFZ_CY.Value = Convert.ToByte(per_arr[1]);
                            Thread.Sleep(5);
                        }
                        else if (perline.Contains("RICKCYCLE"))
                        {
                            perline = perline.Replace("RICKCYCLE", "");
                            string[] per_arr = perline.Split(','); //以逗号分割，添加到数组  
                            int irc_start_ratio = Convert.ToByte(per_arr[0]);
                            int irc_end_ratio = Convert.ToByte(per_arr[1]);
                            int irc_ratio_interval = Convert.ToByte(per_arr[2]);
                            int irc_cycle_count = (int)(Math.Round((double)(irc_end_ratio) / irc_ratio_interval));

                            if (IRC_Measure_Count < irc_cycle_count)
                            {
                                HFZ_Ratio.Value = irc_start_ratio + IRC_Measure_Count * irc_ratio_interval > 100 ? 100 : irc_start_ratio + IRC_Measure_Count * irc_ratio_interval;
                                Thread.Sleep(Convert.ToInt32(CAS200_txt1.Text));
                                btn_CAS200_Synt_Click(btn_CAS200_Measure, null);
                                cbx_follow_text_length_index = cbx_follow_text_length_index - 1;
                                IRC_Measure_Count++;
                            }
                            Thread.Sleep(5);
                        }
                        cbx_follow_text_length_index = cbx_follow_text_length_index + 1;//解析下一行
                        if (cbx_follow_text_length_index < cbx_follow_text_length)
                        {
                            T3.Enabled = true;
                        }
                        else
                        {
                            T3.Enabled = false;
                        }
                    }
                    checkBox1.Checked = true;
                }
                catch
                {
                    T3.Enabled = false;
                    checkBox1.Checked = true;
                    MessageBox.Show("脚本格式有误！");
                }
            }
            else if (cbx_follow_csv.Checked == true)
            {
                //首次测量,统计绝对路径下的BMP list
                if (IRC_Switch_file_flag == true)
                {
                    this.CAS200_dataGridView.Rows.Clear();
                    IRC_PIC_ListBox.SelectedIndex = IRC_ListBox_Index;
                    string filepath = IRC_PIC_ListBox.SelectedItem.ToString();

                    IRC_Switch_file_flag = false;
                    FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
                    // follow_csv_context.Text = filepath;
                    StreamReader streamReader = new StreamReader(fs, Encoding.GetEncoding("GBK"));
                    streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
                    string strLine = streamReader.ReadLine();
                    IRC_picname_list.Clear();
                    while (!string.IsNullOrEmpty(strLine))
                    {
                        string[] arr = strLine.Split(',');
                        IRC_picname_list.Add(arr[0]);
                        strLine = streamReader.ReadLine();
                    }

                    lab_follow_csv_context.Text = "图档数：" + IRC_picname_list.Count.ToString();
                    fs.Close();
                    streamReader.Close();
                    IRC_foldpath = filepath.Substring(0, filepath.LastIndexOf("\\") + 1);
                    IRC_images_counts = 0;
                }

                try
                {
                    Gamma_loading_path.Text = IRC_foldpath;
                    Load_GammmPic(IRC_picname_list[IRC_images_counts].ToString()); //Load pic
                }
                catch
                {
                    MessageBox.Show("不存在图片！");
                    T3.Enabled = false;
                }
                if (PMU_power_print_in_Box_Enable.Checked == true)
                {
                    Thread.Sleep(1200);
                    PMU_OPERATION_Click(btnPowertest, null);
                    Thread.Sleep(100);
                }
                Thread.Sleep(Convert.ToInt16(CAS200_txt1.Text));
                btn_CAS200_Synt_Click(btn_CAS200_Measure, null); //量测   
                IRC_images_counts++;
                if (IRC_images_counts >= IRC_picname_list.Count)
                {
                    //单个文件夹测试完成。自动保存数据
                    if (cbx_follow_csv_auto_save.Checked == true)
                    {
                        // btn_CAS200_Synt_Click(btn_CAS200Save, null);

                        SaveFileDialog sf = new SaveFileDialog(); //对话框
                        sf.Filter = @"csv文件(*.csv)|*.csv|所有文件(*.*)|*.*"; //定义保存的文件的类型
                        string str0 = null;
                        if (cbx_follow_csv_auto_save.Checked == true)
                        {
                            sf.FileName = IRC_foldpath + "configData.csv";
                        }
                        if (sf.FileName == "") return; //如果没有输入文件名
                        try
                        {
                            StreamWriter sw = null; //文件流
                            sw = new StreamWriter(sf.FileName, false, Encoding.UTF8);

                            for (int i = 0; i < (this.CAS200_dataGridView.Rows.Count - 1); i++)
                            {
                                str0 = str0 + this.CAS200_dataGridView.Rows[i].Cells[0].Value.ToString() + ","
                                    + this.CAS200_dataGridView.Rows[i].Cells[1].Value.ToString() + ","
                                    + this.CAS200_dataGridView.Rows[i].Cells[2].Value.ToString() + ","
                                    + this.CAS200_dataGridView.Rows[i].Cells[3].Value.ToString();

                                if (cbo_CASDK_MODE.SelectedIndex == 1)
                                {
                                    str0 = str0 + ","
                                    + this.CAS200_dataGridView.Rows[i].Cells[4].Value.ToString();
                                }

                                if (PMU_power_print_in_Box_Enable.Checked == true || PMU_power_print_in_GradView_Enable.Checked == true)
                                {
                                    str0 = str0 + ","
                                    + this.CAS200_dataGridView.Rows[i].Cells[5].Value.ToString() + ","
                                    + this.CAS200_dataGridView.Rows[i].Cells[6].Value.ToString() + ","
                                    + this.CAS200_dataGridView.Rows[i].Cells[7].Value.ToString() + ","
                                    + this.CAS200_dataGridView.Rows[i].Cells[8].Value.ToString() + ","
                                    + this.CAS200_dataGridView.Rows[i].Cells[9].Value.ToString() + ","
                                    + this.CAS200_dataGridView.Rows[i].Cells[10].Value.ToString() + ","
                                    + this.CAS200_dataGridView.Rows[i].Cells[11].Value.ToString() + ","
                                    + this.CAS200_dataGridView.Rows[i].Cells[12].Value.ToString() + ","
                                    + this.CAS200_dataGridView.Rows[i].Cells[13].Value.ToString() + ","
                                    + this.CAS200_dataGridView.Rows[i].Cells[14].Value.ToString() + ","
                                    + this.CAS200_dataGridView.Rows[i].Cells[15].Value.ToString() + ","
                                    + this.CAS200_dataGridView.Rows[i].Cells[16].Value.ToString() + ","
                                    + this.CAS200_dataGridView.Rows[i].Cells[17].Value.ToString() + ","
                                    + this.CAS200_dataGridView.Rows[i].Cells[18].Value.ToString() + "\r\n";
                                }
                                else
                                {
                                    str0 = str0 + "\r\n";
                                }
                            }

                            sw.WriteLine(str0);
                            sw.Dispose(); //释放资源
                            sw.Close(); //关闭数据流
                                        //   show_LOG_main_msg("测试数据保存OK！", "系统提示：");
                            textBox1.Text += "测试数据保存OK！\r\n";
                        }
                        catch
                        {
                            show_LOG_main_msg("测试数据保存时发生错误，请再试！", "系统提示：");
                        }

                    }
                    IRC_ListBox_Index++;
                    if (IRC_ListBox_Index >= IRC_PIC_ListBox.Items.Count)
                    {
                        T3.Enabled = false; //测试结束
                        textBox1.Text += "测试结束！\r\n";
                        show_LOG_main_msg("测试结束！", "系统提示：");
                    }
                    else
                    {
                        textBox1.Text += "开启新文件夹测试！\r\n";
                        IRC_Switch_file_flag = true; //开启新文件夹测试
                        T3.Enabled = true;
                    }
                }
                else { if (ContinuousLvTestFlag) T3.Enabled = true; }
            }
            else if (cbx_follow_project_gamma_points.Checked == true)
            {
                if (Project_Gamma_Point_Index < Project_Gamma_Point_num)
                {
                    if (checkBox_vesa_bist.Checked == false)
                    {
                        if (rBt_Gamma_W.Checked == true)
                        {
                            checkBox1.Checked = false;
                            numPatternR.Value = numPatternG.Value = numPatternB.Value = Project_Gamma_Point[Project_Gamma_Point_Index];
                        }
                        else if (rBt_Gamma_R.Checked == true)
                        {
                            checkBox1.Checked = false;
                            numPatternR.Value = Project_Gamma_Point[Project_Gamma_Point_Index];
                            numPatternG.Value = 0;
                            numPatternB.Value = 0;
                        }
                        else if (rBt_Gamma_G.Checked == true)
                        {
                            checkBox1.Checked = false;
                            numPatternR.Value = 0;
                            numPatternG.Value = Project_Gamma_Point[Project_Gamma_Point_Index];
                            numPatternB.Value = 0;
                        }
                        else if (rBt_Gamma_B.Checked == true)
                        {
                            checkBox1.Checked = false;
                            numPatternR.Value = 0;
                            numPatternG.Value = 0;
                            numPatternB.Value = Project_Gamma_Point[Project_Gamma_Point_Index];
                        }
                        Pattern_Write((byte)(numPatternR.Value), (byte)(numPatternG.Value), (byte)(numPatternB.Value));
                    }
                    else
                    {
                        if (Gamma_loading_path.Text == "NT37706")
                        {
                            //show_LOG_main_msg("NT37706 Bist pattern test");
                            pattern_index++;

                            if (pattern_index > 0xFF)
                            {
                                T3.Enabled = false;
                                T3.Stop();
                                ContinuousLvTestFlag = false;
                                pattern_index = 0;
                                return;
                            }

                            Generate_textBox.Text = "IC WRITE\r\n" + "EF,00,00," + Convert.ToString(pattern_index, 16) + "," + Convert.ToString(pattern_index, 16) + "," + Convert.ToString(pattern_index, 16);
                            Generate_File_Click(Generate_File_Run, null);
                        }
                    }
                    Project_Gamma_Point_Index++;
                    Thread.Sleep(100);
                    if (PMU_power_print_in_Box_Enable.Checked == true)
                    {
                        Thread.Sleep(1200);
                        PMU_OPERATION_Click(btnPowertest, null);
                        Thread.Sleep(100);
                    }
                    Application.DoEvents();
                    btn_CAS200_Synt_Click(btn_CAS200_Measure, null);
                    Application.DoEvents();
                    if (ContinuousLvTestFlag) T3.Enabled = true;
                }
                else if (Project_Gamma_Point_Index >= Project_Gamma_Point_num)
                {
                    Project_Gamma_Point_Index = 0;
                }
            }
            else if (cbx_follow_register_points.Checked == true)
            {
                Send_buf = new byte[7];
                Send_buf[0] = 0x99;
                Send_buf[1] = 0x10;
                Send_buf[2] = 0x02;
                int reg_frist = Convert.ToInt16(Reg_1.Text, 16);
                int reg_two = Convert.ToInt16(Reg_2.Text, 16);
                int data_frist = Convert.ToInt16(Data_1.Value);
                int data_two = Convert.ToInt16(Data_2.Value);

                Send_buf[3] = byte.Parse(reg_frist.ToString());
                Send_buf[4] = (byte)data_frist;

                CRCData.CalculateCrc16(Send_buf, out Send_buf[5], out Send_buf[6]);
                try
                {
                    comPort.Write(Send_buf, 0, 7);
                    Thread.Sleep(50);
                }
                catch
                {
                    btn_CAS200_Stop.PerformClick();
                    show_LOG_main_msg("测量时串口连接失败！！", "错误");
                }

                if (cbx_follow_register_16bit.Checked == true)
                {
                    Send_buf[3] = byte.Parse(reg_two.ToString());
                    Send_buf[4] = (byte)data_two;
                    CRCData.CalculateCrc16(Send_buf, out Send_buf[5], out Send_buf[6]);
                    try
                    {
                        comPort.Write(Send_buf, 0, 7);
                        Thread.Sleep(50);
                        if (data_two > 0)
                        {
                            Data_2.Value = data_two - Convert.ToInt16(CAS200_txt0.Text);
                            T3.Enabled = true;
                        }
                        else if (data_two == 0 && data_frist > 0)
                        {
                            Data_1.Text = Convert.ToString(data_frist - 1);
                            Data_2.Text = Convert.ToString("FF");
                            T3.Enabled = true;
                        }
                    }
                    catch
                    {
                        btn_CAS200_Stop.PerformClick();
                        show_LOG_main_msg("下指令时串口连接失败！！", "错误");
                    }
                }
                else
                {
                    if (data_frist > 0)
                    {
                        Data_1.Text = Convert.ToString(data_frist - Convert.ToInt32(CAS200_txt0.Text));
                        T3.Enabled = true;
                    }
                }
                btn_CAS200_Synt_Click(btn_CAS200_Measure, null);
            }
            else if (cbx_follow_51_points.Checked == true)
            {
                int bits_51h = CAS200_Measure_Gray;
                Gen_51h_Bits.Text = text_51_bit.Text;
                int total_51h = Convert.ToInt16(Math.Pow(2, Convert.ToByte(Gen_51h_Bits.Text))) - 1;
                int bits_51h_copy = Convert.ToInt16(Gen_51h_Copy_Bits.Text);
                Gen_BC_Bar.Maximum = bits_51h;
                //Gen_BC_lab.Text = tbx_DBV_Type.Text;
                ///dbv亮度条会修改为51、61、63之类的，统一将dbv设定寄存器与设定值进行UI分离。
                Gen_BC_lab_Index.Text = tbx_DBV_Type.Text;
                Gen_BC_lab.Text = "";
                if (total_51h < 0x100)
                {
                    for (int co = 0; co < bits_51h_copy; co++)
                    {
                        Gen_BC_lab.Text = Gen_BC_lab.Text + "" + bits_51h.ToString("x2");
                    }
                }
                else
                {
                    if (checkBoxfan.Checked)   //IC里面的51值高低位相反了   TC1105 谱瑞IC是这样的
                    {
                        for (int co = 0; co < bits_51h_copy; co++)
                        {
                            Gen_BC_lab.Text = Gen_BC_lab.Text + "" + bits_51h.ToString("x4").Substring(2, 2) + "," + bits_51h.ToString("x4").Substring(0, 2);
                        }
                    }
                    else
                    {
                        for (int co = 0; co < bits_51h_copy; co++)
                        {
                            Gen_BC_lab.Text = Gen_BC_lab.Text + "" + bits_51h.ToString("x4").Substring(0, 2) + "," + bits_51h.ToString("x4").Substring(2, 2);
                        }
                    }
                }
                if (bits_51h < 0)
                {
                    Gen_BC_lab.Text = Gen_BC_lab.Text + "00";
                }
                else
                {
                    Gen_DBC_control.Tag = null;
                    if (Gamma_loading_path.Text == "NT37706_AOD_DBV")//for AOD DBV Test, enable this 
                    {
                        Generate_textBox.Text = "IC WRITE\r\n" + "6F,04";
                        Generate_File_Click(Generate_File_Run, null);
                    }

                    Generate_File_Click(Gen_DBC_control, null);
                    textBox1.Text += Gen_BC_lab.Text + "\r\n";
                    textBox1.SelectionStart = this.textBox1.Text.Length;
                    textBox1.ScrollToCaret();//滚动到光标处
                    if (textBox1.Lines.Length > 500) { textBox1.Clear(); }
                    if (Gen_DBC_control.Tag != null) { btn_CAS200_Stop.PerformClick(); }
                }
                if (Convert.ToInt32(text_51_start_bit.Text) > Convert.ToInt32(text_51_end_bit.Text))
                {
                    CAS200_Measure_Gray = CAS200_Measure_Gray - Convert.ToInt32(CAS200_txt0.Text);
                }
                else
                {
                    CAS200_Measure_Gray = CAS200_Measure_Gray + Convert.ToInt32(CAS200_txt0.Text);
                }

                Thread.Sleep(Convert.ToInt16(CAS200_txt1.Text));

                btn_CAS200_Synt_Click(btn_CAS200_Measure, null); //量测

                if (Convert.ToInt32(text_51_start_bit.Text) > Convert.ToInt32(text_51_end_bit.Text))
                {
                    if (CAS200_Measure_Gray < Convert.ToInt32(text_51_end_bit.Text))
                    {
                        T3.Enabled = false;
                    }
                    else { if (ContinuousLvTestFlag) T3.Enabled = true; }
                }
                else
                {
                    if (CAS200_Measure_Gray > Convert.ToInt32(text_51_end_bit.Text))
                    {
                        T3.Enabled = false;
                    }
                    else { if (ContinuousLvTestFlag) T3.Enabled = true; }
                }
            }
            else if (cbx_follow_gamma_vesa_partial.Checked == true)
            {
                Thread.Sleep(50);
                btn_CAS200_Synt_Click(btn_CAS200_Measure, null); //量测

                T3.Enabled = false;
                try
                {
                    if (numPatternR.Value > 0)
                    {
                        numPatternR.Value = (byte)(Convert.ToInt16(numPatternR.Value.ToString()) - int.Parse(CAS200_txt0.Text));
                        if (Convert.ToInt16(numPatternR.Value.ToString()) < int.Parse(CAS200_txt0.Text))
                        {
                            T3.Enabled = false;
                            return;
                        }
                        else
                        {
                            Load_GammmPic(numPatternR.Value.ToString()); //Load pic
                            T3.Enabled = true;
                        }
                    }
                    else if (numPatternR.Value == 0) //已测完
                    {
                        T3.Enabled = false;
                    }
                }
                catch
                {
                    MessageBox.Show("无法找到指定图片！");
                }
            }
            else
            {
                Thread.Sleep(20);
                Application.DoEvents();
                btn_CAS200_Synt_Click(btn_CAS200_Measure, null); //量测
                Application.DoEvents();
                try
                {
                    if ((numPatternR.Value + numPatternB.Value + numPatternG.Value) > 0)
                    {
                        if (rBt_Gamma_W.Checked == true)
                        {
                            checkBox1.Checked = false;
                            numPatternR.Value = (byte)(Convert.ToInt16(numPatternR.Value.ToString()) - int.Parse(CAS200_txt0.Text));
                            numPatternG.Value = (byte)(Convert.ToInt16(numPatternG.Value.ToString()) - int.Parse(CAS200_txt0.Text));
                            numPatternB.Value = (byte)(Convert.ToInt16(numPatternB.Value.ToString()) - int.Parse(CAS200_txt0.Text));
                        }
                        else if (rBt_Gamma_R.Checked == true)
                        {
                            checkBox1.Checked = false;
                            numPatternR.Value = (byte)(Convert.ToInt16(numPatternR.Value.ToString()) - int.Parse(CAS200_txt0.Text));
                            numPatternG.Value = 0;
                            numPatternB.Value = 0;
                        }
                        else if (rBt_Gamma_G.Checked == true)
                        {
                            checkBox1.Checked = false;
                            numPatternR.Value = 0;
                            numPatternG.Value = (byte)(Convert.ToInt16(numPatternG.Value.ToString()) - int.Parse(CAS200_txt0.Text));
                            numPatternB.Value = 0;
                        }
                        else if (rBt_Gamma_B.Checked == true)
                        {
                            checkBox1.Checked = false;
                            numPatternR.Value = 0;
                            numPatternG.Value = 0;
                            numPatternB.Value = (byte)(Convert.ToInt16(numPatternB.Value.ToString()) - int.Parse(CAS200_txt0.Text));
                        }
                        if (ContinuousLvTestFlag)
                        {
                            T3.Enabled = true;
                        }
                    }
                    else
                    {
                        T3.Enabled = false;
                    }
                    Pattern_Write((byte)(numPatternR.Value), (byte)(numPatternG.Value), (byte)(numPatternB.Value));
                    Thread.Sleep(10);
                }
                catch
                {
                    MessageBox.Show("请重置灰阶！");
                }
            }
        }

        private DemuraAutoMeasure frmMeasure = null;
        private void btn_DemuraAutoMeasure_Click(object sender, EventArgs e)
        {

            if (frmMeasure == null || frmMeasure.IsDisposed)
            {
                frmMeasure = new DemuraAutoMeasure(this);//如果之前不存在，则new一个。
                frmMeasure.Show();
            }

            btn_AutoMeasure.Enabled = false;
        }
        private OTP_CODE_GEN frm1 = null;

        private void text_51_bit_TextChanged(object sender, EventArgs e)
        {
            int total_51h = Convert.ToInt16(Math.Pow(2, Convert.ToByte(text_51_bit.Text))) - 1;
            text_51_start_bit.Text = total_51h.ToString();
            Gen_51h_Bits.Text = text_51_bit.Text;
        }

        private void RISK_CRC(byte REG_X, byte REG_Y)
        {
            byte[] X_REG_08H = new byte[144] { 0x0, 0x1, 0x2, 0x3, 0x4, 0x4, 0x4, 0x5, 0x5, 0x5, 0x6, 0x6, 0x6, 0x7, 0x7, 0x7, 0x8, 0x8, 0x9, 0x9, 0xA, 0xA, 0xB, 0xB, 0xE, 0xE, 0xF, 0xF, 0x10, 0x10, 0x11, 0x11, 0x12, 0x12, 0x13, 0x13, 0x14, 0x14, 0x15, 0x15, 0x1F, 0x1F, 0x20, 0x20, 0x21, 0x21, 0x22, 0x22, 0x23, 0x23, 0x24, 0x24, 0x25, 0x25, 0x26, 0x26, 0x3D, 0x3E, 0x3E, 0x3F, 0x3F, 0x40, 0x40, 0x41, 0x41, 0x42, 0x42, 0x43, 0x43, 0x44, 0x44, 0x45, 0xA1, 0xA2, 0xA2, 0xA3, 0xA3, 0xA4, 0xA4, 0xA5, 0xA5, 0xA6, 0xA6, 0xA7, 0xA7, 0xA8, 0xA8, 0xA9, 0xC0, 0xC0, 0xC1, 0xC1, 0xC2, 0xC2, 0xC3, 0xC3, 0xC4, 0xC4, 0xC5, 0xC5, 0xC6, 0xC6, 0xC7, 0xC7, 0xD1, 0xD1, 0xD2, 0xD2, 0xD3, 0xD3, 0xD4, 0xD4, 0xD5, 0xD5, 0xD6, 0xD6, 0xD7, 0xD7, 0xD8, 0xD8, 0xDA, 0xDB, 0xDB, 0xDC, 0xDC, 0xDD, 0xDD, 0xDE, 0xDE, 0xDF, 0xDF, 0xDF, 0xE0, 0xE0, 0xE0, 0xE1, 0xE1, 0xE1, 0xE2, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6 };
            byte[] Y_REG_09H = new byte[144] { 0x4, 0x4, 0x4, 0x4, 0x3, 0x4, 0x5, 0x3, 0x4, 0x5, 0x3, 0x4, 0x5, 0x3, 0x4, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x2, 0x6, 0x2, 0x6, 0x2, 0x6, 0x2, 0x6, 0x2, 0x6, 0x2, 0x6, 0x2, 0x6, 0x2, 0x6, 0x1, 0x7, 0x1, 0x7, 0x1, 0x7, 0x1, 0x7, 0x1, 0x7, 0x1, 0x7, 0x1, 0x7, 0x1, 0x7, 0x8, 0x0, 0x8, 0x0, 0x8, 0x0, 0x8, 0x0, 0x8, 0x0, 0x8, 0x0, 0x8, 0x0, 0x8, 0x0, 0x0, 0x0, 0x8, 0x0, 0x8, 0x0, 0x8, 0x0, 0x8, 0x0, 0x8, 0x0, 0x8, 0x0, 0x8, 0x8, 0x1, 0x7, 0x1, 0x7, 0x1, 0x7, 0x1, 0x7, 0x1, 0x7, 0x1, 0x7, 0x1, 0x7, 0x1, 0x7, 0x2, 0x6, 0x2, 0x6, 0x2, 0x6, 0x2, 0x6, 0x2, 0x6, 0x2, 0x6, 0x2, 0x6, 0x2, 0x6, 0x3, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x4, 0x5, 0x3, 0x4, 0x5, 0x3, 0x4, 0x5, 0x4, 0x5, 0x4, 0x4, 0x4, 0x4 };
            bool RICK_PCS = false;

            for (int i = 0; i < X_REG_08H.Length; i++)
            {
                if ((X_REG_08H[i] == REG_X) && (Y_REG_09H[i] == REG_Y))
                {
                    RICK_PCS = true;
                    break;
                }
            }
            textBox1.Text = textBox1.Text + "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "坐标： " + REG_X.ToString("X") + "," + REG_Y.ToString("X") + "\r\n";
            if (RICK_PCS == true)
            {
                textBox1.Text = textBox1.Text + "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "判定结果：" + "RISK 批次!\r\n";
            }
            else
            {
                textBox1.Text = textBox1.Text + "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "判定结果：" + "OK 批次!\r\n";
            }
        }
        private void Raydium_RISK_Check_Click(object sender, EventArgs e)
        {
            Generate_Read_Result_txt.Text = null;
            Generate_textBox.Text = "IC WRITE\r\n"
                                 + "FE,00\r\n"
                                 + "28\r\n"
                                 + "FE,C0\r\n"
                                 + "DELAY10\r\n"
                                 + "IC READ\r\n"
                                 + "08,01\r\n";
            /*
                                 + "09,01\r\n"
                                 + "DELAY10\r\n"
                                 + "02,01\r\n"
                                 + "03,01\r\n"
                                 + "04,01\r\n"
                                 + "05,01\r\n"
                                 + "06,01\r\n"
                                 + "07,01\r\n"; 
*/
            Application.DoEvents();
            Generate_File_Click(Generate_File_Run, e);
            Thread.Sleep(15);
            Application.DoEvents();
            Generate_Read_Result_txt.Text = null;
            Generate_textBox.Text = "IC WRITE\r\n"
                                 + "FE,C0\r\n"
                                 + "DELAY10\r\n"
                                 + "IC READ\r\n"
                                 + "08,01\r\n"
                                 + "09,01\r\n"
                                 + "DELAY10\r\n"
                                 + "02,01\r\n"
                                 + "03,01\r\n"
                                 + "04,01\r\n"
                                 + "05,01\r\n"
                                 + "06,01\r\n"
                                 + "07,01\r\n"
                                 + "IC WRITE\r\n"
                                 + "FE,00\r\n"
                                 + "29\r\n";
            Application.DoEvents();
            Generate_File_Click(Generate_File_Run, e);
            Thread.Sleep(15);
            Application.DoEvents();
            string strLine = Convert.ToString(Generate_Read_Result_txt.Text);
            string[] arr = strLine.Split(','); //以逗号分割，添加到数组
            byte REG_X = byte.Parse((Convert.ToInt32(arr[1], 16)).ToString());
            byte REG_Y = byte.Parse((Convert.ToInt32(arr[3], 16)).ToString());
            byte wafer_id0 = byte.Parse((Convert.ToInt32(arr[5], 16)).ToString());
            byte wafer_id1 = byte.Parse((Convert.ToInt32(arr[7], 16)).ToString());
            byte wafer_id2 = byte.Parse((Convert.ToInt32(arr[9], 16)).ToString());
            byte wafer_id3 = byte.Parse((Convert.ToInt32(arr[11], 16)).ToString());
            byte wafer_id4 = byte.Parse((Convert.ToInt32(arr[13], 16)).ToString());
            byte wafer_no = byte.Parse((Convert.ToInt32(arr[15], 16)).ToString());
            textBox1.Text = null;
            //获取日期+时间
            textBox1.Text = textBox1.Text + DateTime.Now.ToString() + "\r\n";
            textBox1.Text = textBox1.Text + "ID： " + arr[5] + arr[7] + arr[9] + arr[11] + arr[13] + arr[15] + "\r\n";
            RISK_CRC(REG_X, REG_Y);

            string path = System.Windows.Forms.Application.StartupPath + "Raydium_SRAM_Sorting" + ".txt";
            if (!File.Exists(path))
            {
                FileInfo myfile = new FileInfo(path);
                FileStream fs = myfile.Create();
                fs.Close();
            }
            StreamWriter sw = File.AppendText(path);
            sw.WriteLine(textBox1.Text);
            sw.Flush();
            sw.Close();
        }
        private void OTP_CODE_GEN_Click(object sender, EventArgs e)
        {

            if (frm1 == null || frm1.IsDisposed)
            {
                frm1 = new OTP_CODE_GEN(this);//如果之前不存在，则new一个。
                frm1.Show();
            }

        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (label39.Visible == true)
            {
                label39.Visible = false;
                cBx_VCI_Set.Visible = false;
                label40.Visible = false;
                cBx_VDDI_Set.Visible = false;
            }
            else
            {
                label39.Visible = true;
                //comboBox1.SelectedIndex = 5;
                cBx_VCI_Set.Visible = true;
                label40.Visible = true;
                // comboBox2.SelectedIndex = 2;
                cBx_VDDI_Set.Visible = true;

            }

        }
        private void image_load_path()
        {
            //if (e.KeyCode == Keys.Enter)
            {
                string path = txtPicAddr.Text;
                if (!Directory.Exists(path))
                {
                    MessageBox.Show("文件夹不存在.");
                    return;
                }
                DirectoryInfo di = new DirectoryInfo(path);
                this.listBox3_BMPFile.Items.Clear();
                this.CreateListItem(di);//递归加载文件夹里的所有图片
                                        // textBox2.Text = path;
                                        // -------------------------------------------------------------------------
                StreamWriter sw = null; //文件流
                sw = new StreamWriter("./update/Picaddr.txt", false, Encoding.Default);//Encoding.GetEncoding("UTF-8")
                sw.Write(defaultfilePath);
                sw.Dispose(); //释放资源
                sw.Close(); //关闭数据流

            }
        }

        private void textBox2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
				image_load_path();
            }
        }
        private void UDC_Heavenly_Dragon_Click(object sender, EventArgs e)
        {
            Heavenly_Dragon Dragon_udc = new Heavenly_Dragon(this);
            Dragon_udc.Show();
        }
        private void CommonGamma_BAK_Click(object sender, EventArgs e)
        {
            textBox1.Text = "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "此处功能详情请咨询宋传胜";
        }

        ////替代弹窗报警：MessageBox.Show("串口有误，请检查", "错误");    
        public void show_LOG_main_msg(string str, string logtype)//log打印，根据不同勾选，分类型打印log
        {
            string nowtime = DateTime.Now.Year.ToString("D4") + "-" + DateTime.Now.Month.ToString("D2") + "-" + DateTime.Now.Day.ToString("D2") + " " + DateTime.Now.Hour.ToString("D2") + ":" + DateTime.Now.Minute.ToString("D2") + ":" + DateTime.Now.Second.ToString("D2") + "." + DateTime.Now.Millisecond.ToString("D3");//当前系统时间，精确到毫秒

            textBox1.Text += "\r\n" + logtype + ":  " + "\r\n";
            textBox1.Text += "[" + nowtime + "]:  " + str + "\r\n";
        }

        private void CommonGamma_Click(object sender, EventArgs e)
        {
            if (AGengamma_Form == null || AGengamma_Form.IsDisposed)
            {
                AGengamma_Form = new AGengamma(this);//如果之前不存在，则new一个。
                AGengamma_Form.Show();
            }
            else
            {
                AGengamma_Form.Show();
                AGengamma_Form.Activate();//之前已打开，则给予焦点，置顶。
            }
        }
        public void common_gamma_function(string str_code)
        {
            if (AGengamma_Form == null || AGengamma_Form.IsDisposed)
            {
                AGengamma_Form = new AGengamma(this);//如果之前不存在，则new一个。
                AGengamma_Form.show_script_cmd(str_code);
                AGengamma_Form.Show();
            }
            else
            {
                AGengamma_Form.show_script_cmd(str_code);
                AGengamma_Form.Show();
                AGengamma_Form.Activate();//之前已打开，则给予焦点，置顶。
            }
        }
        private void radioButton8bit_MouseEnter(object sender, EventArgs e)
        {
            ToolTip p = new ToolTip();
            p.ShowAlways = true;
            p.SetToolTip(this.radioButton8bit, "正常下寄存器的地址去读");
        }

        private void CA310Modelauto_CheckedChanged(object sender, EventArgs e)
        {
            if (CaSDK_Measure_Speed.SelectedIndex == 0) CaSDKObj.ca310speed = 3; //AUTO
            else if (CaSDK_Measure_Speed.SelectedIndex == 1) CaSDKObj.ca310speed = 1; //FAST
            else if (CaSDK_Measure_Speed.SelectedIndex == 2) CaSDKObj.ca310speed = 0; //SLOW
            else if (CaSDK_Measure_Speed.SelectedIndex == 3) CaSDKObj.ca310speed = 2; //LTD_AUTO
            //    const int SLOW = 0;
            //const int FAST = 1;
            //const int LTD_AUTO = 2;
            //const int AUTO = 3;
        }

        private void 隐秘的角落ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SD_write SD = new SD_write(this);
            SD.ShowDialog();
        }

        private void chkSizeCheck_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {

            }
            else
            {
                if (chkFastSendBmp.Enabled)
                { chkFastSendBmp.Enabled = false; }
                else
                {
                    chkFastSendBmp.Enabled = true;
                }
            }
        }
        private string Compare_me;
        private void Gen_DBV_Demura_Test_Bar_Scroll(object sender, EventArgs e)
        {
            int bits_51h = Convert.ToInt16(Math.Pow(2, Convert.ToByte(Gen_51h_Demura_Bits_Test.Text))) - 1;

            Gen_DBV_Demura_Test_Bar.Maximum = bits_51h;
            try
            {
                if (bits_51h < 0x100)
                {
                    Gen_BC_lab_test.Text = "" + Gen_DBV_Demura_Test_Bar.Value.ToString("x2");
                }
                else
                {
                    Gen_BC_lab_test.Text = "" + "" + Gen_DBV_Demura_Test_Bar.Value.ToString("x4").Substring(0, 2) + "," + Gen_DBV_Demura_Test_Bar.Value.ToString("x4").Substring(2, 2);
                }
                //  if (rdo_DBV_Normal_Mode.Checked == true)
                //  {
                //FFF
                if (Gen_DBV_Demura_Test_Bar.Value > Convert.ToInt16((DBV_Node5.Text.Substring(3, 2) + DBV_Node5.Text.Substring(6, 2)), 16))
                {
                    if (!string.Equals(Compare_me, DBV_Node_Cmd5.Text))
                    {
                        Compare_me = DBV_Node_Cmd5.Text;
                        txtCmd3.Text = DBV_Node_Cmd5.Text;
                        Send_Cmd_Click(btnSend3, null);
                    }
                } //7FF
                else if (Gen_DBV_Demura_Test_Bar.Value <= Convert.ToInt16((DBV_Node5.Text.Substring(3, 2) + DBV_Node5.Text.Substring(6, 2)), 16) && Gen_DBV_Demura_Test_Bar.Value > Convert.ToInt16((DBV_Node4.Text.Substring(3, 2) + DBV_Node4.Text.Substring(6, 2)), 16))
                {
                    if (!string.Equals(Compare_me, DBV_Node_Cmd5.Text))
                    {
                        Compare_me = DBV_Node_Cmd5.Text;
                        txtCmd3.Text = DBV_Node_Cmd5.Text;
                        Send_Cmd_Click(btnSend3, null);
                        Thread.Sleep(15);
                    }
                }//5FF
                else if (Gen_DBV_Demura_Test_Bar.Value <= Convert.ToInt16((DBV_Node4.Text.Substring(3, 2) + DBV_Node4.Text.Substring(6, 2)), 16) && Gen_DBV_Demura_Test_Bar.Value > Convert.ToInt16((DBV_Node3.Text.Substring(3, 2) + DBV_Node3.Text.Substring(6, 2)), 16))
                {
                    if (!string.Equals(Compare_me, DBV_Node_Cmd4.Text))
                    {
                        Compare_me = DBV_Node_Cmd4.Text;
                        txtCmd3.Text = DBV_Node_Cmd4.Text;
                        Send_Cmd_Click(btnSend3, null);
                        Thread.Sleep(15);
                    }
                }//4FF
                else if (Gen_DBV_Demura_Test_Bar.Value <= Convert.ToInt16((DBV_Node3.Text.Substring(3, 2) + DBV_Node3.Text.Substring(6, 2)), 16) && Gen_DBV_Demura_Test_Bar.Value > Convert.ToInt16((DBV_Node2.Text.Substring(3, 2) + DBV_Node2.Text.Substring(6, 2)), 16))
                {
                    if (!string.Equals(Compare_me, DBV_Node_Cmd3.Text))
                    {
                        Compare_me = DBV_Node_Cmd3.Text;
                        txtCmd3.Text = DBV_Node_Cmd3.Text;
                        Send_Cmd_Click(btnSend3, null);
                        Thread.Sleep(15);
                    }
                }
                else if (Gen_DBV_Demura_Test_Bar.Value <= Convert.ToInt16((DBV_Node2.Text.Substring(3, 2) + DBV_Node2.Text.Substring(6, 2)), 16) && Gen_DBV_Demura_Test_Bar.Value > Convert.ToInt16((DBV_Node1.Text.Substring(3, 2) + DBV_Node1.Text.Substring(6, 2)), 16))
                {
                    if (!string.Equals(Compare_me, DBV_Node_Cmd2.Text))
                    {
                        Compare_me = DBV_Node_Cmd2.Text;
                        txtCmd3.Text = DBV_Node_Cmd2.Text;
                        Send_Cmd_Click(btnSend3, null);
                        Thread.Sleep(15);
                    }
                }
                else if (Gen_DBV_Demura_Test_Bar.Value <= Convert.ToInt16((DBV_Node1.Text.Substring(3, 2) + DBV_Node1.Text.Substring(6, 2)), 16) && Gen_DBV_Demura_Test_Bar.Value > Convert.ToInt16((DBV_Node0.Text.Substring(3, 2) + DBV_Node0.Text.Substring(6, 2)), 16))
                {
                    if (!string.Equals(Compare_me, DBV_Node_Cmd1.Text))
                    {
                        Compare_me = DBV_Node_Cmd1.Text;
                        txtCmd3.Text = DBV_Node_Cmd1.Text;
                        Send_Cmd_Click(btnSend3, null);
                        Thread.Sleep(15);
                    }
                }
                else if (Gen_DBV_Demura_Test_Bar.Value <= Convert.ToInt16((DBV_Node0.Text.Substring(3, 2) + DBV_Node0.Text.Substring(6, 2)), 16) && Gen_DBV_Demura_Test_Bar.Value > Convert.ToInt16((DBV_Node.Text.Substring(3, 2) + DBV_Node.Text.Substring(6, 2)), 16))
                {
                    if (!string.Equals(Compare_me, DBV_Node_Cmd0.Text))
                    {
                        Compare_me = DBV_Node_Cmd0.Text;
                        txtCmd3.Text = DBV_Node_Cmd0.Text;
                        Send_Cmd_Click(btnSend3, null);
                        Thread.Sleep(15);
                    }
                }
                else if (Gen_DBV_Demura_Test_Bar.Value <= Convert.ToInt16((DBV_Node.Text.Substring(3, 2) + DBV_Node.Text.Substring(6, 2)), 16))
                {
                    if (!string.Equals(Compare_me, DBV_Node_Cmd.Text))
                    {
                        Compare_me = DBV_Node_Cmd.Text;
                        txtCmd3.Text = DBV_Node_Cmd.Text;
                        Send_Cmd_Click(btnSend3, null);
                        Thread.Sleep(15);
                    }
                }
                /*
            }
            else //DC mode
            {
                if (Generate_textBox.Text != DBV_Node_Cmd5.Text)
                {
                    Generate_textBox.Text = DBV_Node_Cmd5.Text;
                    Generate_File_Click(Generate_File_Run, null);
                }
            }*/
                Gen_DBV_Demura_Test_Click(null, null);
            }
            catch
            {
                // MessageBox.Show("K位深不支持！");
            }
        }
        private void Gen_DBV_Demura_Test_Click(object sender, EventArgs e)
        {
            try
            {
                string strLine0 = Convert.ToString(Gen_BC_lab_test.Text);
                string[] arr0 = strLine0.Split(','); //以逗号分割，添加到数组

                Setting.TempRecord.cmdLen = arr0.Length + 5;
                Send_buf = new byte[arr0.Length + 5];
                Send_buf[0] = 0x3E; //
                Send_buf[1] = 0x01; //寄存器写
                Send_buf[2] = byte.Parse(arr0.Length.ToString());
                for (int i = 0; i < arr0.Length; i++)
                {
                    Send_buf[3 + i] = byte.Parse((Convert.ToInt32(arr0[i], 16)).ToString());
                }
                CRCData.CalculateCrc16(Send_buf, out Send_buf[Send_buf[2] + 3], out Send_buf[Send_buf[2] + 4]);
                try
                {
                    comPort.Write(Send_buf, 0, Send_buf[2] + 5);
                }
                catch
                {
                    show_LOG_main_msg("串口有误，请检查", "错误");
                }
            }
            catch
            {
                show_LOG_main_msg("输入格式错误！", "错误");
            }
        }

        private void toolTip2_Popup(object sender, PopupEventArgs e)
        {

        }
        private void cbx_51shortcut_key_KeyDown(object sender, KeyEventArgs e)
        {
            string filter = "/";
            string a = tbx_51shortcut_key.Text.Replace(filter, " ");
            string[] arr_gamma_51code = a.Trim().Split(' ');
            string Gamma_51testcode = null;
            if (cbx_51shortcut_key.Checked == true)
            {
                if (e.KeyCode == Keys.Q)
                {
                    try
                    {
                        Gamma_51testcode = "51," + arr_gamma_51code[0].Insert(2, ",");
                        txtProcessDrivercode(Gamma_51testcode, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        if (rBt_LP_DCS_Long_Write.Checked | rBt_LP_DCS_Short_Write.Checked | rBt_LP_Gerneric_Long_Write.Checked | rBt_LP_Gerneric_Short_Write.Checked)
                        {
                            SendCmd(0);
                        }
                        else
                        {
                            SendCmd(4);
                        }
                        textBox1.Text += "命令已下发...\r\n";
                        textBox1.Select(textBox1.Text.Length, 0);
                        textBox1.ScrollToCaret();

                    }
                    catch
                    {
                        MessageBox.Show("该键位没有设置合理的51值，请检查输入内容");
                    }

                }
                else if (e.KeyCode == Keys.W)
                {
                    try
                    {
                        Gamma_51testcode = "51," + arr_gamma_51code[1].Insert(2, ",");
                        txtProcessDrivercode(Gamma_51testcode, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        if (rBt_LP_DCS_Long_Write.Checked | rBt_LP_DCS_Short_Write.Checked | rBt_LP_Gerneric_Long_Write.Checked | rBt_LP_Gerneric_Short_Write.Checked)
                        {
                            SendCmd(0);
                        }
                        else
                        {
                            SendCmd(4);
                        }
                        textBox1.Text += "命令已下发...\r\n";
                        textBox1.Select(textBox1.Text.Length, 0);
                        textBox1.ScrollToCaret();

                    }
                    catch
                    {
                        MessageBox.Show("该键位没有设置合理的51值，请检查输入内容");
                    }
                }
                else if (e.KeyCode == Keys.E)
                {
                    try
                    {
                        Gamma_51testcode = "51," + arr_gamma_51code[2].Insert(2, ",");
                        txtProcessDrivercode(Gamma_51testcode, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        if (rBt_LP_DCS_Long_Write.Checked | rBt_LP_DCS_Short_Write.Checked | rBt_LP_Gerneric_Long_Write.Checked | rBt_LP_Gerneric_Short_Write.Checked)
                        {
                            SendCmd(0);
                        }
                        else
                        {
                            SendCmd(4);
                        }
                        textBox1.Text += "命令已下发...\r\n";
                        textBox1.Select(textBox1.Text.Length, 0);
                        textBox1.ScrollToCaret();

                    }
                    catch
                    {
                        MessageBox.Show("该键位没有设置合理的51值，请检查输入内容");
                    }
                }
                else if (e.KeyCode == Keys.R)
                {
                    try
                    {
                        Gamma_51testcode = "51," + arr_gamma_51code[3].Insert(2, ",");
                        txtProcessDrivercode(Gamma_51testcode, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        if (rBt_LP_DCS_Long_Write.Checked | rBt_LP_DCS_Short_Write.Checked | rBt_LP_Gerneric_Long_Write.Checked | rBt_LP_Gerneric_Short_Write.Checked)
                        {
                            SendCmd(0);
                        }
                        else
                        {
                            SendCmd(4);
                        }
                        textBox1.Text += "命令已下发...\r\n";
                        textBox1.Select(textBox1.Text.Length, 0);
                        textBox1.ScrollToCaret();

                    }
                    catch
                    {
                        MessageBox.Show("该键位没有设置合理的51值，请检查输入内容");
                    }
                }
                else if (e.KeyCode == Keys.T)
                {
                    try
                    {
                        Gamma_51testcode = "51," + arr_gamma_51code[4].Insert(2, ",");
                        txtProcessDrivercode(Gamma_51testcode, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        if (rBt_LP_DCS_Long_Write.Checked | rBt_LP_DCS_Short_Write.Checked | rBt_LP_Gerneric_Long_Write.Checked | rBt_LP_Gerneric_Short_Write.Checked)
                        {
                            SendCmd(0);
                        }
                        else
                        {
                            SendCmd(4);
                        }
                        textBox1.Text += "命令已下发...\r\n";
                        textBox1.Select(textBox1.Text.Length, 0);
                        textBox1.ScrollToCaret();

                    }
                    catch
                    {
                        MessageBox.Show("该键位没有设置合理的51值，请检查输入内容");
                    }
                }
                else if (e.KeyCode == Keys.Y)
                {
                    try
                    {
                        Gamma_51testcode = "51," + arr_gamma_51code[5].Insert(2, ",");
                        txtProcessDrivercode(Gamma_51testcode, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        if (rBt_LP_DCS_Long_Write.Checked | rBt_LP_DCS_Short_Write.Checked | rBt_LP_Gerneric_Long_Write.Checked | rBt_LP_Gerneric_Short_Write.Checked)
                        {
                            SendCmd(0);
                        }
                        else
                        {
                            SendCmd(4);
                        }
                        textBox1.Text += "命令已下发...\r\n";
                        textBox1.Select(textBox1.Text.Length, 0);
                        textBox1.ScrollToCaret();

                    }
                    catch
                    {
                        MessageBox.Show("该键位没有设置合理的51值，请检查输入内容");
                    }
                }
                else if (e.KeyCode == Keys.U)
                {
                    try
                    {
                        Gamma_51testcode = "51," + arr_gamma_51code[6].Insert(2, ",");
                        txtProcessDrivercode(Gamma_51testcode, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        if (rBt_LP_DCS_Long_Write.Checked | rBt_LP_DCS_Short_Write.Checked | rBt_LP_Gerneric_Long_Write.Checked | rBt_LP_Gerneric_Short_Write.Checked)
                        {
                            SendCmd(0);
                        }
                        else
                        {
                            SendCmd(4);
                        }
                        textBox1.Text += "命令已下发...\r\n";
                        textBox1.Select(textBox1.Text.Length, 0);
                        textBox1.ScrollToCaret();

                    }
                    catch
                    {
                        MessageBox.Show("该键位没有设置合理的51值，请检查输入内容");
                    }
                }
                else if (e.KeyCode == Keys.I)
                {
                    try
                    {
                        Gamma_51testcode = "51," + arr_gamma_51code[7].Insert(2, ",");
                        txtProcessDrivercode(Gamma_51testcode, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        if (rBt_LP_DCS_Long_Write.Checked | rBt_LP_DCS_Short_Write.Checked | rBt_LP_Gerneric_Long_Write.Checked | rBt_LP_Gerneric_Short_Write.Checked)
                        {
                            SendCmd(0);
                        }
                        else
                        {
                            SendCmd(4);
                        }
                        textBox1.Text += "命令已下发...\r\n";
                        textBox1.Select(textBox1.Text.Length, 0);
                        textBox1.ScrollToCaret();

                    }
                    catch
                    {
                        MessageBox.Show("该键位没有设置合理的51值，请检查输入内容");
                    }
                }
                else if (e.KeyCode == Keys.O)
                {
                    try
                    {
                        Gamma_51testcode = "51," + arr_gamma_51code[8].Insert(2, ",");
                        txtProcessDrivercode(Gamma_51testcode, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        if (rBt_LP_DCS_Long_Write.Checked | rBt_LP_DCS_Short_Write.Checked | rBt_LP_Gerneric_Long_Write.Checked | rBt_LP_Gerneric_Short_Write.Checked)
                        {
                            SendCmd(0);
                        }
                        else
                        {
                            SendCmd(4);
                        }
                        textBox1.Text += "命令已下发...\r\n";
                        textBox1.Select(textBox1.Text.Length, 0);
                        textBox1.ScrollToCaret();

                    }
                    catch
                    {
                        MessageBox.Show("该键位没有设置合理的51值，请检查输入内容");
                    }
                }
                else if (e.KeyCode == Keys.P)
                {
                    try
                    {
                        Gamma_51testcode = "51," + arr_gamma_51code[9].Insert(2, ",");
                        txtProcessDrivercode(Gamma_51testcode, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        if (rBt_LP_DCS_Long_Write.Checked | rBt_LP_DCS_Short_Write.Checked | rBt_LP_Gerneric_Long_Write.Checked | rBt_LP_Gerneric_Short_Write.Checked)
                        {
                            SendCmd(0);
                        }
                        else
                        {
                            SendCmd(4);
                        }
                        textBox1.Text += "命令已下发...\r\n";
                        textBox1.Select(textBox1.Text.Length, 0);
                        textBox1.ScrollToCaret();

                    }
                    catch
                    {
                        MessageBox.Show("该键位没有设置合理的51值，请检查输入内容");
                    }
                }
            }
        }
        private void tbx_51shortcut_key_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                string filter = "/";
                string a = tbx_51shortcut_key.Text.Replace(filter, " ");
                string[] arr_gamma_51code = a.Trim().Split(' ');
                tbx_51shortcut_key.Text = "";
                for (int i = 0; i < arr_gamma_51code.Length; i++)
                {
                    arr_gamma_51code[i].ToUpper();
                    if (arr_gamma_51code[i].Length == 1)
                    {
                        arr_gamma_51code[i] = "000" + arr_gamma_51code[i];
                    }
                    else if (arr_gamma_51code[i].Length == 2)
                    {
                        arr_gamma_51code[i] = "00" + arr_gamma_51code[i];
                    }
                    else if (arr_gamma_51code[i].Length == 3)
                    {
                        arr_gamma_51code[i] = "0" + arr_gamma_51code[i];
                    }
                    else if (arr_gamma_51code[i].Length > 4)
                    {
                        arr_gamma_51code[i] = arr_gamma_51code[i].Substring(arr_gamma_51code[i].Length - 4);
                    }
                    if (i == 0)
                    {
                        tbx_51shortcut_key.Text = arr_gamma_51code[i];
                    }
                    else
                    {
                        tbx_51shortcut_key.Text = tbx_51shortcut_key.Text + "/" + arr_gamma_51code[i];
                    }
                }
            }
        }

        private void cbx_shortcut_txtcmd_MouseEnter(object sender, EventArgs e)
        {
            ToolTip p = new ToolTip();
            p.ShowAlways = true;
            p.SetToolTip(this.cbx_shortcut_txtcmd, "勾选后开启下方8个窗体write快捷键，1—8窗体分别对应QWERTYUI");
        }
        private void cbx_shortcut_txtcmd_KeyDown(object sender, KeyEventArgs e)
        {
            if (cbx_shortcut_txtcmd.Checked == true)
            {
                if (e.KeyCode == Keys.Q)
                {
                    Send_Cmd_Click(btnSend1, e);
                }
                else if (e.KeyCode == Keys.W)
                {
                    Send_Cmd_Click(btnSend2, e);
                }
                else if (e.KeyCode == Keys.E)
                {
                    Send_Cmd_Click(btnSend3, e);
                }
                else if (e.KeyCode == Keys.R)
                {
                    Send_Cmd_Click(btnSend4, e);
                }
                else if (e.KeyCode == Keys.T)
                {
                    Send_Cmd_Click(btnSend5, e);
                }
                else if (e.KeyCode == Keys.Y)
                {
                    Send_Cmd_Click(btnSend6, e);
                }
                else if (e.KeyCode == Keys.U)
                {
                    Send_Cmd_Click(btnSend7, e);
                }
                else if (e.KeyCode == Keys.I)
                {
                    Send_Cmd_Click(btnSend8, e);
                }
                else
                {
                    MessageBox.Show("该键位没有设置快捷键");
                }
            }

        }

        private void cbx_shortcut_txtcmd_Leave(object sender, EventArgs e)
        {
            cbx_shortcut_txtcmd.Checked = false;
        }

        private void cbx_51shortcut_key_Leave(object sender, EventArgs e)
        {
            cbx_51shortcut_key.Checked = false;
        }
        private void Cbxlogic_go_CheckedChanged(object sender, EventArgs e)
        {
            if (cbxlogic_go.Checked == true)
            {
                btnPatternW.BackColor = Color.Gold;
            }
            else
            {
                btnPatternW.BackColor = SystemColors.Menu;
            }
        }
        private void HFZ_CXY_ValueChanged(object sender, EventArgs e)
        {
            HFZ_CX.Maximum = HACT.Value;
            HFZ_CY.Maximum = VACT.Value;
            switch (CBX_HFZ_LOGIC.SelectedIndex)
            {
                case 0:
                    {
                        double m_x = Math.Sqrt(Convert.ToDouble(HFZ_Ratio.Value) / 100) * Convert.ToInt16(HACT.Value) / 2;
                        double m_y = Math.Sqrt(Convert.ToDouble(HFZ_Ratio.Value) / 100) * Convert.ToInt16(VACT.Value) / 2;
                        HFZ_X0.Value = HFZ_CX.Value - (decimal)(m_x) < 0 ? 0 : (uint)(HFZ_CX.Value - (decimal)(m_x));
                        HFZ_X1.Value = HFZ_CX.Value + (decimal)(m_x) < 0 ? 0 : (uint)(HFZ_CX.Value + (decimal)(m_x));
                        HFZ_Y0.Value = HFZ_CY.Value - (decimal)(m_y) < 0 ? 0 : (uint)(HFZ_CY.Value - (decimal)(m_y));
                        HFZ_Y1.Value = HFZ_CY.Value + (decimal)(m_y) < 0 ? 0 : (uint)(HFZ_CY.Value + (decimal)(m_y));
                    }
                    break;
                case 1: //round
                    {
                        HFZ_X0.Value = HFZ_CX.Value;//(decimal)((double)(Convert.ToInt16(HACT.Value)) / 2);
                        HFZ_Y0.Value = HFZ_CY.Value;//(decimal)((double)(Convert.ToInt16(VACT.Value)) / 2);
                    }
                    break;
                case 4: //2 round
                    {
                        HFZ_X0.Value = HFZ_CX.Value;//(decimal)((double)(Convert.ToInt16(HACT.Value)) / 2);
                        HFZ_Y0.Value = HFZ_CY.Value;//(decimal)((double)(Convert.ToInt16(VACT.Value)) / 2);
                    }
                    break;
                default:
                    {
                        HFZ_CX.Value = (decimal)((double)(Convert.ToInt16(HACT.Value)) / 2);
                        HFZ_CY.Value = (decimal)((double)(Convert.ToInt16(VACT.Value)) / 2);
                    }
                    break;
            }
            decimal b_x = HFZ_CX.Value <= (HACT.Value / 2) ? Math.Abs(HACT.Value - HFZ_CX.Value) * 2 : HFZ_CX.Value * 2;
            decimal b_y = HFZ_CY.Value <= (VACT.Value / 2) ? Math.Abs(VACT.Value - HFZ_CY.Value) * 2 : HFZ_CY.Value * 2;
            HFZ_EXP_XRatio.Text = ((double)(b_x) / (double)(HACT.Value)).ToString();
            HFZ_EXP_YRatio.Text = ((double)(b_y) / (double)(VACT.Value)).ToString();
            OLED_Show_Click(btnlogic_go, e);
        }
        private void Btnlogic_location_go_Click(object sender, EventArgs e)
        {
            Logic_SeekXY SeekXY = new Logic_SeekXY(this);
            SeekXY.ShowDialog();
        }
        private void btnlogic_default_Click(object sender, EventArgs e)
        {
            try
            {
                HFZ_CX.Value = (decimal)((double)(Convert.ToInt16(HACT.Value)) / 2);
                HFZ_CY.Value = (decimal)((double)(Convert.ToInt16(VACT.Value)) / 2);
            }
            catch
            {; }
        }
        private void Btnlogic_pattern_saveout(object sender, EventArgs e)
        {
            int points_num = 0;
            int[] HFZ_Point = new int[500];
            Array.Clear(HFZ_Point, 0, HFZ_Point.Length);
            string logicpath = null;
            string result = null;
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.FileName = "Logic.bmp";
            dialog.Filter = "Logic(*.bmp)|*.bmp";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                logicpath = dialog.FileName;
            }
            if (cBx_HFZ_Batch_Saveout.Checked == true)//批量导出
            {
                string[] str = tBx_HFZ_Batch.Lines;
                try
                {
                    for (int i = 0; i < str.Length; i++)
                    {
                        string line = str[i];
                        line = line.Replace(" ", "");
                        string[] arr0 = str[i].Split(',');
                        for (int j = 0; j < arr0.Length; j++)
                        {
                            HFZ_Point[points_num++] = Convert.ToInt16(arr0[j]);
                        }
                    }
                }
                catch
                {
                    show_LOG_main_msg("输入格式错误！！", "错误");
                }
                int k = 0;
                while (k < points_num)
                {
                    if (rBt_HFZ_Mc.Checked == true)
                    {
                        if (rbt_HFZ_Color_W.Checked == true)
                        {
                            HFZ_M_R.Value = HFZ_Point[k];
                            HFZ_M_G.Value = HFZ_Point[k];
                            HFZ_M_B.Value = HFZ_Point[k];
                        }
                        else if (rbt_HFZ_Color_R.Checked == true)
                        {
                            HFZ_M_R.Value = HFZ_Point[k];
                        }
                        else if (rbt_HFZ_Color_G.Checked == true)
                        {
                            HFZ_M_G.Value = HFZ_Point[k];
                        }
                        else if (rbt_HFZ_Color_B.Checked == true)
                        {
                            HFZ_M_B.Value = HFZ_Point[k];
                        }
                    }
                    else
                    {
                        if (rbt_HFZ_Color_W.Checked == true)
                        {
                            HFZ_L_R.Value = HFZ_Point[k];
                            HFZ_L_G.Value = HFZ_Point[k];
                            HFZ_L_B.Value = HFZ_Point[k];
                        }
                        else if (rbt_HFZ_Color_R.Checked == true)
                        {
                            HFZ_L_R.Value = HFZ_Point[k];
                        }
                        else if (rbt_HFZ_Color_G.Checked == true)
                        {
                            HFZ_L_G.Value = HFZ_Point[k];
                        }
                        else if (rbt_HFZ_Color_B.Checked == true)
                        {
                            HFZ_L_B.Value = HFZ_Point[k];
                        }
                    }
                    result = logicpath;
					if(logicpath != null)
					{
	                    result = result.Insert(logicpath.LastIndexOf('.'), HFZ_Point[k].ToString());
					}
                    HFZ_Logic_to_Pattern(result);
                    progressBar4.Value = Convert.ToInt32((double)k / (points_num - 1) * 100);
                    k++;
                }
            }
            else
            {
                HFZ_Logic_to_Pattern(logicpath);
            }

			if(logicpath != null)//save logic pic OK
			{
				txtPicAddr.Text = logicpath.Substring(0, logicpath.LastIndexOf("\\"));
				image_load_path();
			}
        }

        private void Btnlogic_go_preview_Leave(object sender, EventArgs e)
        {
            pictureBox2.Visible = false;
        }
        private void Btnlogic_pattern_preview(object sender, EventArgs e)
        {
            pictureBox2.Visible = true;
            HFZ_Logic_to_Pattern("Perview");
        }
        void HFZ_Logic_to_Pattern(string path)
        {
            int logicWidth = (int)HACT.Value;
            int logicHeight = (int)VACT.Value;
            int logicWidth_n = logicWidth % 4 + logicWidth;
            byte[] LogicData = new byte[logicWidth_n * 3 * logicHeight];
            byte[,] LogicData_R = new byte[logicHeight, logicWidth_n];
            byte[,] LogicData_G = new byte[logicHeight, logicWidth_n];
            byte[,] LogicData_B = new byte[logicHeight, logicWidth_n];
            int rx3, ry3, rr3;
            int pix_count = 0;
            try
            {
                switch (CBX_HFZ_LOGIC.SelectedIndex)
                {
                    case 0: //方形
                        {
                            for (int y = 0; y < logicHeight; y++)
                            {
                                for (int x = 0; x < logicWidth_n; x++)
                                {
                                    if (x >= HFZ_X0.Value && x < HFZ_X1.Value && y >= HFZ_Y0.Value && y < HFZ_Y1.Value)
                                    {
                                        LogicData_R[y, x] = (byte)(HFZ_L_R.Value);
                                        LogicData_G[y, x] = (byte)(HFZ_L_G.Value);
                                        LogicData_B[y, x] = (byte)(HFZ_L_B.Value);
                                    }
                                    else
                                    {
                                        LogicData_R[y, x] = (byte)(HFZ_M_R.Value);
                                        LogicData_G[y, x] = (byte)(HFZ_M_G.Value);
                                        LogicData_B[y, x] = (byte)(HFZ_M_B.Value);
                                    }
                                    LogicData[pix_count + 2] = LogicData_R[y, x];
                                    LogicData[pix_count + 1] = LogicData_G[y, x];
                                    LogicData[pix_count] = LogicData_B[y, x];
                                    pix_count = pix_count + 3;
                                }
                            }
                        }
                        break;
                    case 1:
                        {
                            for (int y = 0; y < logicHeight; y++) //行开始
                            {
                                for (int x = 0; x < logicWidth_n; x++)
                                {
                                    if ((x - HFZ_X0.Value) * (x - HFZ_X0.Value) + (y - HFZ_Y0.Value) * (y - HFZ_Y0.Value) <= HFZ_R.Value * HFZ_R.Value)
                                    {
                                        LogicData_R[y, x] = (byte)(HFZ_L_R.Value);
                                        LogicData_G[y, x] = (byte)(HFZ_L_G.Value);
                                        LogicData_B[y, x] = (byte)(HFZ_L_B.Value);
                                    }
                                    else
                                    {
                                        LogicData_R[y, x] = (byte)(HFZ_M_R.Value);
                                        LogicData_G[y, x] = (byte)(HFZ_M_G.Value);
                                        LogicData_B[y, x] = (byte)(HFZ_M_B.Value);
                                    }
                                    LogicData[pix_count + 2] = LogicData_R[y, x];
                                    LogicData[pix_count + 1] = LogicData_G[y, x];
                                    LogicData[pix_count] = LogicData_B[y, x];
                                    pix_count = pix_count + 3;
                                }
                            }
                        }
                        break;
                    case 2:
                        {
                            for (int y = 0; y < logicHeight; y++) //行开始
                            {
                                for (int x = 0; x < logicWidth_n; x++)
                                {
                                    rx3 = (int)(x - (HFZ_X1.Value - HFZ_X0.Value) / 2 - HFZ_X0.Value);
                                    ry3 = (int)(y - (HFZ_Y1.Value - HFZ_Y0.Value) / 2 - HFZ_Y0.Value);
                                    rr3 = (int)(HFZ_R.Value);
                                    if (rx3 * rx3 + ry3 * ry3 <= rr3 * rr3 & (y < HFZ_Y0.Value - 1 | y > HFZ_Y1.Value | x < HFZ_X0.Value - 1 | x > HFZ_X1.Value - 2))
                                    {
                                        LogicData_R[y, x] = (byte)(HFZ_L_R.Value);
                                        LogicData_G[y, x] = (byte)(HFZ_L_G.Value);
                                        LogicData_B[y, x] = (byte)(HFZ_L_B.Value);
                                    }
                                    else
                                    {
                                        LogicData_R[y, x] = (byte)(HFZ_M_R.Value);
                                        LogicData_G[y, x] = (byte)(HFZ_M_G.Value);
                                        LogicData_B[y, x] = (byte)(HFZ_M_B.Value);
                                    }
                                    LogicData[pix_count + 2] = LogicData_R[y, x];
                                    LogicData[pix_count + 1] = LogicData_G[y, x];
                                    LogicData[pix_count] = LogicData_B[y, x];
                                    pix_count = pix_count + 3;
                                }
                            }
                        }
                        break;
                    case 3:
                        {
                            for (int y = 0; y < logicHeight; y++) //行开始
                            {
                                for (int x = 0; x < logicWidth_n; x++)
                                {
                                    if (y == HFZ_Y0.Value - 1 | x == HFZ_X0.Value - 1)
                                    {
                                        LogicData_R[y, x] = (byte)(HFZ_L_R.Value);
                                        LogicData_G[y, x] = (byte)(HFZ_L_G.Value);
                                        LogicData_B[y, x] = (byte)(HFZ_L_B.Value);
                                    }
                                    else
                                    {
                                        LogicData_R[y, x] = (byte)(HFZ_M_R.Value);
                                        LogicData_G[y, x] = (byte)(HFZ_M_G.Value);
                                        LogicData_B[y, x] = (byte)(HFZ_M_B.Value);
                                    }
                                    LogicData[pix_count + 2] = LogicData_R[y, x];
                                    LogicData[pix_count + 1] = LogicData_G[y, x];
                                    LogicData[pix_count] = LogicData_B[y, x];
                                    pix_count = pix_count + 3;
                                }
                            }
                        }
                        break;
                    default:
                        break;
                }
                IntPtr pData = Marshal.AllocHGlobal(logicWidth_n * logicHeight * 3);
                Marshal.Copy(LogicData, 0, pData, logicWidth_n * logicHeight * 3);
                Bitmap bmplogic = new Bitmap(logicWidth, logicHeight, logicWidth_n * 3, PixelFormat.Format24bppRgb, pData);
                if (path == "Perview")
                {
                    pictureBox2.Image = bmplogic;
                }
                else
                {
                    bmplogic.Save(path, ImageFormat.Bmp);
                }
            }
            catch
            {
                MessageBox.Show("图片导出失败！");
            }
        }

        private void HFZ_M_R_ValueChanged(object sender, EventArgs e)
        {
            if (cBx_Logic_rgb_same.Checked == true)
            {
                HFZ_M_G.Value = HFZ_M_R.Value;
                HFZ_M_B.Value = HFZ_M_R.Value;
            }
        }
        private void HFZ_M_G_ValueChanged(object sender, EventArgs e)
        {
            if (cBx_Logic_rgb_same.Checked == true)
            {
                HFZ_M_R.Value = HFZ_M_G.Value;
                HFZ_M_B.Value = HFZ_M_G.Value;
            }
        }

        private void HFZ_M_B_ValueChanged(object sender, EventArgs e)
        {
            if (cBx_Logic_rgb_same.Checked == true)
            {
                HFZ_M_R.Value = HFZ_M_B.Value;
                HFZ_M_G.Value = HFZ_M_B.Value;
            }
        }

        private void HFZ_L_R_ValueChanged(object sender, EventArgs e)
        {
            if (cBx_Logic_rgb_same.Checked == true)
            {
                HFZ_L_B.Value = HFZ_L_R.Value;
                HFZ_L_G.Value = HFZ_L_R.Value;
            }
        }
        private void HFZ_L_G_ValueChanged(object sender, EventArgs e)
        {
            if (cBx_Logic_rgb_same.Checked == true)
            {
                HFZ_L_B.Value = HFZ_L_G.Value;
                HFZ_L_R.Value = HFZ_L_G.Value;
            }
        }

        private void HFZ_L_B_ValueChanged(object sender, EventArgs e)
        {
            if (cBx_Logic_rgb_same.Checked == true)
            {
                HFZ_L_G.Value = HFZ_L_B.Value;
                HFZ_L_R.Value = HFZ_L_B.Value;
            }
        }

        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            byte[] InitiateFile = new byte[20];
            Int16 tep = 0;
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            byte[] FileHead = System.Text.Encoding.Default.GetBytes("Logic_Config.CFG");
            byte[] FileEnd = System.Text.Encoding.Default.GetBytes("Logic_CFGEND");
            saveFileDialog1.FileName = "Logic_Config.CFG";
            saveFileDialog1.Filter = "Logic_Cfg File(*.cfg)|*.cfg";
            saveFileDialog1.FilterIndex = 2;
            saveFileDialog1.RestoreDirectory = true;
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                System.IO.FileStream fs = (System.IO.FileStream)saveFileDialog1.OpenFile();//输出文件
                Array.Clear(InitiateFile, 0, 20);
                Array.Copy(FileHead, InitiateFile, FileHead.Length);

                InitiateFile[0] = Convert.ToByte(CBX_HFZ_LOGIC.SelectedIndex);
                InitiateFile[1] = Convert.ToByte(HFZ_M_R.Value);
                InitiateFile[2] = Convert.ToByte(HFZ_M_G.Value);
                InitiateFile[3] = Convert.ToByte(HFZ_M_B.Value);
                InitiateFile[4] = Convert.ToByte(HFZ_L_R.Value);
                InitiateFile[5] = Convert.ToByte(HFZ_L_G.Value);
                InitiateFile[6] = Convert.ToByte(HFZ_L_B.Value);
                tep = Convert.ToInt16(HFZ_X0.Value);
                InitiateFile[7] = (byte)(tep >> 8);
                InitiateFile[8] = (byte)(tep);
                tep = Convert.ToInt16(HFZ_X1.Value);
                InitiateFile[9] = (byte)(tep >> 8);
                InitiateFile[10] = (byte)(tep);
                tep = Convert.ToInt16(HFZ_Y0.Value);
                InitiateFile[11] = (byte)(tep >> 8);
                InitiateFile[12] = (byte)(tep);
                tep = Convert.ToInt16(HFZ_Y1.Value);
                InitiateFile[13] = (byte)(tep >> 8);
                InitiateFile[14] = (byte)(tep);
                tep = Convert.ToInt16(HFZ_R.Value);
                InitiateFile[15] = (byte)(tep >> 8);
                InitiateFile[16] = (byte)(tep);
                InitiateFile[17] = (byte)(cbxlogic_go.Checked == true ? 1 : 0);
                InitiateFile[18] = (byte)(cbxlogic_go_rgb_swap.Checked == true ? 1 : 0);
                fs.Write(InitiateFile, 0, 19);
                fs.Close();
            }
        }

        private void 载入ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            byte[] TemFileContent = new byte[20];
            double tep = 0;
            System.Int32 ByteReaded = 0x00;
            OpenFileDialog of = new OpenFileDialog();
            of.Filter = @"cfg文件(*.cfg)|*.cfg|所有文件(*.*)|*.*"; ;
            of.Title = "载入配置文件";
            try
            {
                if (of.ShowDialog() == DialogResult.OK)
                {
                    //读取文本信息
                    FileStream fs = new FileStream(of.FileName, FileMode.Open, FileAccess.Read);
                    fs.Seek(0, SeekOrigin.Begin);
                    ByteReaded = fs.Read(TemFileContent, 0, 20);//读取文件从地址0的20个数据
                    CBX_HFZ_LOGIC.SelectedIndex = TemFileContent[0];
                    HFZ_M_R.Value = TemFileContent[1];
                    HFZ_M_G.Value = TemFileContent[2];
                    HFZ_M_B.Value = TemFileContent[3];
                    HFZ_L_R.Value = TemFileContent[4];
                    HFZ_L_G.Value = TemFileContent[5];
                    HFZ_L_B.Value = TemFileContent[6];
                    HFZ_X0.Value = (TemFileContent[7] << 8) + TemFileContent[8];
                    HFZ_X1.Value = (TemFileContent[9] << 8) + TemFileContent[10];
                    HFZ_Y0.Value = (TemFileContent[11] << 8) + TemFileContent[12];
                    HFZ_Y1.Value = (TemFileContent[13] << 8) + TemFileContent[14];
                    HFZ_R.Value = (TemFileContent[15] << 8) + TemFileContent[16];
                    cbxlogic_go.Checked = TemFileContent[17] == 1 ? true : false;
                    cbxlogic_go_rgb_swap.Checked = TemFileContent[18] == 1 ? true : false;
                    fs.Close();
                }
            }
            catch
            {
                MessageBox.Show("配置内容错误！");
            }
        }

        private void HFZ_Ratio_ValueChanged(object sender, EventArgs e)
        {
            if (CBX_HFZ_LOGIC.SelectedIndex == 0) //方
            {
                //  HFZ_X0.Value = (decimal)(Math.Round(Convert.ToDouble(HACT.Value) - (double)(Math.Sqrt(Convert.ToDouble(HFZ_Ratio.Value) / 100)) * Convert.ToInt16(HACT.Value)) / 2);
                //  HFZ_X1.Value = (decimal)(Convert.ToDouble(HACT.Value) - Convert.ToDouble(HFZ_X0.Value));
                //  HFZ_Y0.Value = (decimal)(Math.Round(Convert.ToDouble(VACT.Value) - (double)(Math.Sqrt(Convert.ToDouble(HFZ_Ratio.Value) / 100)) * Convert.ToInt16(VACT.Value)) / 2);
                //  HFZ_Y1.Value = (decimal)(Convert.ToDouble(VACT.Value) - Convert.ToDouble(HFZ_Y0.Value));

                double m_x = Math.Sqrt(Convert.ToDouble(HFZ_Ratio.Value) / 100) * Convert.ToInt16(HACT.Value) / 2 * Convert.ToDouble(HFZ_EXP_XRatio.Text);
                double m_y = Math.Sqrt(Convert.ToDouble(HFZ_Ratio.Value) / 100) * Convert.ToInt16(VACT.Value) / 2 * Convert.ToDouble(HFZ_EXP_YRatio.Text);
                HFZ_X0.Value = HFZ_CX.Value - (decimal)(m_x) < 0 ? 0 : (uint)(HFZ_CX.Value - (decimal)(m_x));
                HFZ_X1.Value = HFZ_CX.Value + (decimal)(m_x) < 0 ? 0 : (uint)(HFZ_CX.Value + (decimal)(m_x));
                HFZ_Y0.Value = HFZ_CY.Value - (decimal)(m_y) < 0 ? 0 : (uint)(HFZ_CY.Value - (decimal)(m_y));
                HFZ_Y1.Value = HFZ_CY.Value + (decimal)(m_y) < 0 ? 0 : (uint)(HFZ_CY.Value + (decimal)(m_y));
            }
            else if (CBX_HFZ_LOGIC.SelectedIndex == 1)
            {
                HFZ_X0.Value = HFZ_CX.Value;//(decimal)((double)(Convert.ToInt16(HACT.Value)) / 2);
                HFZ_Y0.Value = HFZ_CY.Value;//(decimal)((double)(Convert.ToInt16(VACT.Value)) / 2);
                HFZ_R.Value = (decimal)(Math.Sqrt((double)(Convert.ToInt16(HACT.Value)) * Convert.ToInt16(VACT.Value) * Convert.ToInt16(HFZ_Ratio.Value) * Convert.ToDouble(HFZ_EXP_XRatio.Text) * Convert.ToDouble(HFZ_EXP_YRatio.Text) / 100 / Math.PI));
            }
            OLED_Show_Click(btnlogic_go, e);
        }

        private void Rdo_DBV_Normal_Mode_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton btnTmp = (RadioButton)sender;
            switch (btnTmp.Name)
            {
                case "rdo_DBV_Normal_Mode":
                    {
                        Generate_textBox.Text = DBV_Node_Cmd6.Text;
                        Generate_File_Click(Generate_File_Run, null);
                    }
                    break;
                case "rdo_DBV_DC_Mode":
                    {
                        Generate_textBox.Text = DBV_Node_Cmd7.Text;
                        Generate_File_Click(Generate_File_Run, null);
                    }
                    break;
            }
        }

        public void btnDisplayOFF_Click(object sender, EventArgs e)
        {
            string tepstr;
            tepstr = txtSourcecode.Text;
            txtSourcecode.Text = "28\r\nff,ff,ff,20\r\n10\r\nff,ff,ff,20";
            btnDDicDriverDownload_Click(btnDDicDriverDownload, null);
            txtSourcecode.Text = tepstr;
        }


        private void Save_BridgeCode(object sender, EventArgs e)
        {
            SaveFileDialog sf = new SaveFileDialog(); //对话框
            sf.Filter = @"txt文件(*.txt)|*.txt|所有文件(*.*)|*.*"; //定义保存的文件的类型
            string str = "保存Bridge Code文件";
            if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
            {
                if (sf.FileName == "") return; //如果没有输入文件名
                StreamWriter sw = null; //文件流
                sw = new StreamWriter(sf.FileName, false, Encoding.UTF8);
                try
                {
                    for (int i = 0; i < lstMIPISSD.Items.Count; i++)     //IC 初始化代码
                    {
                        str = lstMIPISSD.Items[i].ToString();
                        sw.WriteLine(str);
                    }
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流
                    show_LOG_main_msg("Bridge Code保存OK！", "系统提示：");
                }
                catch
                {
                    show_LOG_main_msg("Bridge Code保存时发生错误，请再试！", "系统提示：");
                }
            }
        }

        private void 保存BridgeSCMCodeToolStripMenuItem_Click(object sender, EventArgs e)
        {

            SaveFileDialog sf = new SaveFileDialog(); //对话框
            sf.Filter = @"txt文件(*.txt)|*.txt|所有文件(*.*)|*.*"; //定义保存的文件的类型
            string str = "保存Bridge SCM Code文件";
            if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
            {
                if (sf.FileName == "") return; //如果没有输入文件名
                StreamWriter sw = null; //文件流
                sw = new StreamWriter(sf.FileName, false, Encoding.UTF8);
                try
                {
                    for (int i = 0; i < lstCPHY_SCM.Items.Count; i++)     //IC 初始化代码
                    {
                        str = lstCPHY_SCM.Items[i].ToString();
                        sw.WriteLine(str);
                    }
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流
                    show_LOG_main_msg("Bridge SCM Code保存OK！", "系统提示：");
                }
                catch
                {
                    show_LOG_main_msg("Bridge SCM Code保存时发生错误，请再试！", "系统提示：");
                }
            }
        }

        private void Dis_mode_SelectedIndexChanged_1(object sender, EventArgs e)
        {
            if (Dis_mode.SelectedIndex == 0)//cmd_mode
            {
                rBt_LP_DCS_Short_Write.Checked = true;
            }
            else
            {
                rBt_HS_DCS_Short_Write.Checked = true;
            }
        }

        private void 内嵌GammaToolToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string tabName = "HFGenGamma";

            if (!IsOpenTab(tabName))
            {

                AGengamma doc = new AGengamma(this);
                doc.MdiParent = this;
                doc.WindowState = FormWindowState.Maximized;
                doc.Show();
                doc.Update();
            }
        }

        /// <summary>
        /// 防止打开多个同样的子窗体,检查是否已打开某个子窗体,如果打开了就返回true,否则返回false
        /// </summary>
        /// <param name="tabName">子窗体的窗体名称</param>
        /// <returns></returns>
        private bool IsOpenTab(string tabName)
        {
            bool isOpened = false;

            foreach (TabPage tab in ss.TabPages)
            {
                if (tab.Text.Trim() == tabName)
                {
                    isOpened = true;
                    ss.SelectedTab = tab;
                    break;
                }
            }

            return isOpened;
        }
        public TCPIP_JCCam frmTCPIP_JCCam;
        private void frmTCPIP_JCCam_Load()
        {
            if (frmTCPIP_JCCam == null)
            {
                frmTCPIP_JCCam = new TCPIP_JCCam();//给窗体变量赋值
                frmTCPIP_JCCam.TopLevel = false;
                frmTCPIP_JCCam.FormBorderStyle = FormBorderStyle.None;
            }
            frmTCPIP_JCCam.Show();
            //清除之前加载的控件
            tabTCP.Controls.Clear();
            //加载窗体1控件
            tabTCP.Controls.Add(frmTCPIP_JCCam);
            //
            this.frmTCPIP_JCCam.Dock = System.Windows.Forms.DockStyle.Fill;
        }
        public frmRGB frmRGBtab;
        private void frmRGB_Load()
        {
            if (frmRGBtab == null)
            {
                frmRGBtab = new frmRGB();//给窗体变量赋值
                frmRGBtab.TopLevel = false;
                frmRGBtab.FormBorderStyle = FormBorderStyle.None;
            }
            frmRGBtab.Show();
            //清除之前加载的控件
            tabDemuraIP.Controls.Clear();
            //加载窗体1控件
            tabDemuraIP.Controls.Add(frmRGBtab);
            //
            this.frmRGBtab.Dock = System.Windows.Forms.DockStyle.Fill;
        }
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (textBox1.Lines.Length > 16)
            {
                textBox1.Select(textBox1.Text.Length, 0);
                textBox1.ScrollToCaret();
            }
        }

        private void Cbx_logic_pic_index_SelectedIndexChanged(object sender, EventArgs e)
        {
            OLED_Show_Click(btnlogic_pic, null);
        }

        private void radioButton16bit_MouseEnter(object sender, EventArgs e)
        {
            ToolTip p = new ToolTip();
            p.ShowAlways = true;
            p.SetToolTip(this.radioButton16bit, "需要下page地址+寄存器的地址去读");
        }

        private void checkBoxfan_MouseEnter(object sender, EventArgs e)
        {
            ToolTip p = new ToolTip();
            p.ShowAlways = true;
            p.SetToolTip(this.checkBoxfan, "51调光，高低位会相反，慎用!!!");
        }

        private void Rbt_PMU_mA_Gear_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton btnTmp = (RadioButton)sender;
            Send_buf = new byte[38];
            Setting.TempRecord.cmdLen = 38; //33+5
            Send_buf[0] = 0x9E;
            Send_buf[1] = 0x05; //lock
            Send_buf[2] = 33;  //length
            Send_buf[3] = 0x02; //oled功耗测量-电流档位切换

            if (rbt_PMU_mA_Gear.Checked == true)
            {
                Send_buf[4] = 0x00;//mA档
            }
            else if (rbt_PMU_uA_Gear.Checked == true)
            {
                Send_buf[4] = 0x01; //uA档
            }
            CRCData.CalculateCrc16(Send_buf, out Send_buf[36], out Send_buf[37]);
            {
                try
                {
                    comPort.Write(Send_buf, 0, 38);
                }
                catch
                {
                    show_LOG_main_msg("串口有误，请检查", "错误");
                }
                T1.Enabled = false;
                T1.Interval = 500;
                T1.Enabled = true;
            }
        }

        public void BtnGrayShow_Click(object sender, EventArgs e)
        {
            #region   //画灰阶图
            Bitmap bm = new Bitmap((int)(HACT.Value), (int)(VACT.Value), PixelFormat.Format24bppRgb);//确定bnp的轮廓1080*2340               
            Graphics g = Graphics.FromImage(bm);
            int N;//每个灰阶所占的行数
            N = (int)(bm.Height / ((gray_level.Value - gray_level_low.Value) + 1));
            int s = (int)gray_level_low.Value - 1;//最低灰阶位 gray_level_low
            //画灰阶图
            for (int m = 0; m < VACT.Value; m++)
            {
                if ((m % N == 0) && (s < gray_level.Value))//每被整除一次s进一
                {
                    s = s + 1;
                }
                SolidBrush brush = new SolidBrush(Color.FromArgb(s, s, s));//设置笔刷的属性，颜色
                g.FillRectangle(brush, 0, m, (int)(HACT.Value), 1);//横条    g.FillRectangle(brush, 0, j, 1080, 1);
                                                                   // FillRectangle(Brush brush, int x, int y, int width, int height);//水平方向为x,竖直方向为y,如直角坐标
            }
            //写灰阶号 
            SolidBrush brush1 = new SolidBrush(Color.FromArgb(0, 128, 0));//设置笔刷的属性，颜色 //字体属性
            string graynum = "";
            //Font myFont = new Font("宋体", 15);//实例化Font对象 设置字号大小
            Font myFont = new Font("宋体", (int)font_size.Value);//实例化Font对象 设置字号大小 
            //Graphics g1 = Graphics.FromImage(bm);

            int k = (int)gray_level_low.Value - 1;
            for (int m = 0; m < VACT.Value; m = m + N)
            {
                if (m % N == 0)   //每被整除一次s进一
                {
                    k = k + 1;
                }

                if (k >= gray_level.Value)  //k加到限制的灰阶后，保持为限制的灰阶
                {
                    k = (int)(gray_level.Value);
                }

                graynum = k.ToString();
                g.DrawString(graynum, myFont, brush1, 100, m);//绘制文本 （x,y）=  (100, j)字体起点
                                                              //g.FillRectangle(brush1, 0, j, Convert.ToInt32(txt_Width.Text), 1);//横条   //画一条分割线
                                                              // g.FillRectangle(brush1, 0, j, 20, 1);//横条   //画一条分割线
                g.FillRectangle(brush1, 100, m, 20, 1);//横条   //画一条分割线
            }
            this.pictureBox1.Image = bm;//读取bm到picturebox
            ///create_my_file();//创建文件夹
            //bm.Save(@".\vertical_gray_10.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
            #endregion
            MemoryStream aFile;
            aFile = new MemoryStream();
            bm.Save(aFile, System.Drawing.Imaging.ImageFormat.Bmp);
            aFile.Seek(0, SeekOrigin.Begin);//            aFile.Position = 0;             
            Int32 HACT_True;
            Int32 VACT_True;
            Int32 m_txlen = 0;
            Int32 j;
            //FileStream aFile;
            byte[] TemFileContent = new byte[1024 * 100];
            System.Int32 ByteReaded = 0x00;
            #region
            //------------20180808---------------
            try
            { //5a a5 9DF0731A-----提前下个标志位告诉下位机开始送图了，避免特殊图片格式导致错误配置
                TemFileContent[0] = 0xbd; TemFileContent[1] = 0x5a; TemFileContent[2] = 0xa5; TemFileContent[3] = 0x9d; TemFileContent[4] = 0xf0;
                comPort.Write(TemFileContent, 0, 5);
            }
            catch
            {
                show_LOG_main_msg("串口有误，请检查", "错误");
                return;
            }
            //-----------------------------------
            #endregion
            try
            {
                ByteReaded = aFile.Read(TemFileContent, 0, 54);
                HACT_True = (Convert.ToInt32(TemFileContent[19]) << 8) + TemFileContent[18];
                VACT_True = Convert.ToInt32((TemFileContent[23] << 8) + TemFileContent[22]);
                if ((HACT.Value != HACT_True))
                {
                    textBox1.Text += "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "图片宽度与设定不符\r\n";
                    return;
                }
                j = 1;
                {
                    // aFile.Seek(54, SeekOrigin.Begin);
                    while (j <= VACT_True)
                    {
                        if (HACT_True % 4 != 0)
                            aFile.Seek((VACT_True - j) * (HACT_True * 3 + (HACT_True % 4)) + 54, SeekOrigin.Begin);
                        else
                            aFile.Seek((VACT_True - j) * HACT_True * 3 + 54, SeekOrigin.Begin);

                        ByteReaded = aFile.Read(TemFileContent, 0, HACT_True * 3); // 
                        try
                        {
                            comPort.Write(TemFileContent, 0, ByteReaded);
                        }
                        catch
                        {
                            show_LOG_main_msg("串口有误，请检查", "错误");
                            break;
                        }
                        m_txlen += ByteReaded;
                        progressBar1.Value = Convert.ToInt32((double)m_txlen / aFile.Length * 100);
                        label14.Text = progressBar1.Value.ToString() + "%";
                        Application.DoEvents();//重点，必须加上，否则父子窗体都假死
                        j++;
                    }
                    TemFileContent[0] = 0x5A;
                    try
                    {
                        comPort.Write(TemFileContent, 0, 1);
                    }
                    catch
                    {
                        show_LOG_main_msg("串口有误，请检查", "错误");
                        return;
                    }
                    aFile.Close();
                }
            }
            catch
            {
                textBox1.Text += "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "啥图片都没显示";
                textBox1.Select(textBox1.Text.Length, 0);
                textBox1.ScrollToCaret();
            }

        }
        private void Gray_level_low_ValueChanged(object sender, EventArgs e)
        {
            if (gray_level_low.Value >= gray_level.Value)
            {
                if (gray_level.Value > 0)
                    gray_level_low.Value = gray_level.Value - 1;
                else
                {
                    gray_level_low.Value = 0;
                    gray_level.Value = 1;
                }
            }
        }

        private void cbx_follow_project_gamma_points_CheckedChanged(object sender, EventArgs e)
        {
            Array.Clear(Project_Gamma_Point, 0, Project_Gamma_Point.Length);
            Project_Gamma_Point_num = 0;
            Project_Gamma_Point_Index = 0;
            string[] str = tBx_project_gamma_points_define.Lines;
            try
            {
                for (int i = 0; i < str.Length; i++)
                {
                    string line = str[i];
                    line = line.Replace(" ", "");
                    string[] arr0 = str[i].Split(',');
                    for (int j = 0; j < arr0.Length; j++)
                    {
                        Project_Gamma_Point[Project_Gamma_Point_num++] = Convert.ToInt16(arr0[j]);
                    }
                }
            }
            catch
            {
                cbx_follow_project_gamma_points.Checked = false;
                show_LOG_main_msg("输入格式错误！！", "错误");
            };
        }

        public bool PMU_MAX_Check(object sender, EventArgs e)
        {
           ////随时检测电流是否超限值，超规限值之后，将电流值至0，返回值报false错误
            if ((DVDDC) > (MAX_DVDDC))
            {
                show_LOG_main_msg("因 DVDD 电流问题已断电！\r\n", "错误提示");
                DVDDC = 0;
                return false;
            }
            if ((VCIC) > (MAX_VCIC))
            {
                show_LOG_main_msg("因 VCI 电流问题已断电！\r\n", "错误提示");
                VCIC = 0;
                return false;
            }
            if ((VDDIOC) > (MAX_VDDIOC))
            {
                show_LOG_main_msg("因 VDDIO 电流问题已断电！\r\n", "错误提示");
                VDDIOC = 0;
                return false;
            }
            if ((ELVDDC) > (MAX_ELVDDC))
            {
                show_LOG_main_msg("因 ELVDD 电流问题已断电！\r\n", "错误提示");
                ELVDDC = 0;
                ELVSSC = 0;
                return false;
            }
            if ((ELVSSC) > (MAX_ELVSSC))
            {
                show_LOG_main_msg("因 ELVDD 电流问题已断电！\r\n", "错误提示");
                ELVSSC = 0;
                ELVDDC = 0;
                return false;
            }
            if ((AVDDC) > (MAX_AVDDC))
            {
                show_LOG_main_msg("因 AVDD 电流问题已断电！\r\n", "错误提示");
                AVDDC = 0;
                return false;
            }

            return true;
        }

        public void PMU_OPERATION_Click(object sender, EventArgs e)
        {
            Button btnTmp = (Button)sender;
            Send_buf = new byte[38];
            Setting.TempRecord.cmdLen = 38; //33+5
            Send_buf[0] = 0x9E;
            Send_buf[1] = 0x05; //lock
            Send_buf[2] = 33; //length
            Send_buf[4] = 0x00;
            if (rbtnCoarse.Checked == true)   //粗调标志位
            {
                Send_buf[4] |= 0x1;
            }
            switch (btnTmp.Name)
            {
                case "btnPowertest":
                    {
                        Send_buf[3] = 0x00; //oled功耗测量
                    }
                    break;
                case "btnVDDDown":
                    {
                        if (cbx_PMU_measure_DVDD.Checked == false)
                        {
                            Send_buf[3] = 0x01; //输出校准
                            Send_buf[4] |= 0x2;
                        }
                        else if (cbx_PMU_measure_DVDD.Checked == true)
                        {
                            Send_buf[3] = 0x01;
                            Send_buf[5] |= 0x20;
                        }

                    }
                    break;
                case "btnVDDUp":
                    {
                        if (cbx_PMU_measure_DVDD.Checked == false)
                        {
                            Send_buf[3] = 0x01; //输出校准
                            Send_buf[4] |= 0x4;
                        }
                        else if (cbx_PMU_measure_DVDD.Checked == true)
                        {
                            Send_buf[3] = 0x01;
                            Send_buf[5] |= 0x40;
                        }

                    }
                    break;
                case "btnVDDIODown":
                    {
                        Send_buf[3] = 0x01; //输出校准
                        Send_buf[5] |= 0x2;
                    }
                    break;
                case "btnVDDIOUp":
                    {
                        Send_buf[3] = 0x01; //输出校准
                        Send_buf[5] |= 0x4;
                    }
                    break;
                case "btnPower_print":
                    {
                        SaveFileDialog sf = new SaveFileDialog(); //对话框
                        sf.Filter = @"txt文件(*.txt)|*.txt|所有文件(*.*)|*.*"; //定义保存的文件的类型
                        string str = "功耗数据：\r\n";
                        if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
                        {
                            if (sf.FileName == "") return; //如果没有输入文件名
                            try
                            {
                                StreamWriter sw = null; //文件流
                                sw = new StreamWriter(sf.FileName, false, Encoding.UTF8);
                                str = str + "VCI " + "电压值：" + PMU_listView.Items[0].SubItems[1].Text + " " + PMU_listView.Items[0].SubItems[2].Text + "," + "电流值：" + PMU_listView.Items[0].SubItems[3].Text + " " + PMU_listView.Items[0].SubItems[4].Text + " " + "\r\n";
                                str = str + "VDDI " + "电压值：" + PMU_listView.Items[1].SubItems[1].Text + " " + PMU_listView.Items[1].SubItems[2].Text + "," + "电流值：" + PMU_listView.Items[1].SubItems[3].Text + " " + PMU_listView.Items[1].SubItems[4].Text + " " + "\r\n";
                                str = str + "AVDD " + "电压值：" + PMU_listView.Items[2].SubItems[1].Text + " " + PMU_listView.Items[2].SubItems[2].Text + "," + "电流值：" + PMU_listView.Items[2].SubItems[3].Text + " " + PMU_listView.Items[2].SubItems[4].Text + " " + "\r\n";
                                str = str + "ELVSS " + "电压值：" + PMU_listView.Items[3].SubItems[1].Text + " " + PMU_listView.Items[3].SubItems[2].Text + "," + "电流值：" + PMU_listView.Items[3].SubItems[3].Text + " " + PMU_listView.Items[3].SubItems[4].Text + " " + "\r\n";
                                str = str + "ELVDD " + "电压值：" + PMU_listView.Items[4].SubItems[1].Text + " " + PMU_listView.Items[4].SubItems[2].Text + "," + "电流值：" + PMU_listView.Items[4].SubItems[3].Text + " " + PMU_listView.Items[4].SubItems[4].Text + " " + "\r\n";
                                str = str + "VBAT " + "电压值：" + PMU_listView.Items[5].SubItems[1].Text + " " + PMU_listView.Items[5].SubItems[2].Text + "," + "电流值：" + PMU_listView.Items[5].SubItems[3].Text + " " + PMU_listView.Items[5].SubItems[4].Text + " " + "\r\n";
                                str = str + "DVDD " + "电压值：" + PMU_listView.Items[6].SubItems[1].Text + " " + PMU_listView.Items[6].SubItems[2].Text + "," + "电流值：" + PMU_listView.Items[6].SubItems[3].Text + " " + PMU_listView.Items[6].SubItems[4].Text + " " + "\r\n";
                                str = str + "IC功耗：" + PMU_ddic_power_print.Text + " mW" + "\r\n";
                                str = str + "屏体功耗：" + PMU_panel_power_print.Text + " mW" + "\r\n";
                                str = str + "模组功耗：" + PMU_power_print.Text + " mW" + "\r\n";
                                sw.WriteLine(str);
                                sw.Dispose(); //释放资源
                                sw.Close(); //关闭数据流
                                show_LOG_main_msg("功耗数据保存OK！", "系统提示：");
                            }
                            catch
                            {
                                show_LOG_main_msg("功耗数据保存时发生错误，请再试！", "系统提示：");
                            }
                        }
                        return;
                    }
                    //break;
            }
            CRCData.CalculateCrc16(Send_buf, out Send_buf[36], out Send_buf[37]);
            if (!this.comPort.IsOpen)
            {
                try
                {
                    comPort.PortName = Detection.GetComNum();
                    comPort.BaudRate = Setting.ComSet.comBaudRate;
                    this.openSerialPort(true);
                }
                catch
                {
                    Tim_Powertest.Enabled = false;
                    chkAutoPowertest.Checked = false;
                    show_LOG_main_msg("没有搜索到串口！", "错误提示");
                }
            }
            else
            {
                try
                {
                    comPort.Write(Send_buf, 0, 38);
                }
                catch
                {
                    Tim_Powertest.Enabled = false;
                    chkAutoPowertest.Checked = false;
                    show_LOG_main_msg("串口有误，请检查", "错误");
                }

                T1.Enabled = false;
                T1.Interval = 50000;
                T1.Enabled = true;
                if (PMU_MAX_Check(null, null) == false)
                {
                    ////检测到电流超限值，进行reset动作。
                    chkAutoPowertest.Checked = false;////关闭电流连续测量模式。
                    PMU_MAX_Check(null, null);
                    show_LOG_main_msg("因电流问题已断电！\r\n", "错误提示");
                    LCD_Reset_Click(btnLCDcfg, e);/////关闭供电。。
                }
            }
        }

        private void Tim_Powertest_Tick(object sender, EventArgs e)
        {
            PMU_OPERATION_Click(btnPowertest, e);
        }
        private void ChkAutoPowertest_CheckedChanged(object sender, EventArgs e)
        {
            if (chkAutoPowertest.Checked == true)
            {
                Tim_Powertest.Enabled = true;
            }
            else
            {
                Tim_Powertest.Enabled = false;
            }
        }
        private void BtnGetSSD2832Reg_Click(object sender, EventArgs e)
        {
            string strTmp;
            Send_buf = new byte[10];
            Setting.TempRecord.cmdLen = 10;
            Send_buf[0] = 0x1D;
            Send_buf[1] = 0x05;
            Send_buf[2] = 0x03;
            strTmp = txtMIPISSD.Text.Substring(0, 2);
            Send_buf[3] = byte.Parse((Convert.ToInt32(strTmp, 16)).ToString());
            //4\5\6\7
            CRCData.CalculateCrc16(Send_buf, out Send_buf[8], out Send_buf[9]);
            try
            {
                comPort.Write(Send_buf, 0, 10);
            }
            catch
            {
                show_LOG_main_msg("串口有误，请检查", "错误");
            }

            T1.Enabled = false;
            T1.Interval = 500;
            T1.Enabled = true;
        }
        private void Mode_Shift_Enable_CheckedChanged(object sender, EventArgs e)
        {
            if (Mode_Shift_Enable.Checked == false)
            {
                btnLCDcfg.Text = "RESET";
            }
            else
            {
                btnLCDcfg.Text = "模式切换";
            }
        }
        private void Btn_EE_Edit_Function_Click(object sender, EventArgs e)
        {
            Button btnTmp = (Button)sender;
            Send_buf = new byte[15];
            Setting.TempRecord.cmdLen = 15; //
            Send_buf[0] = 0x90;
            Send_buf[1] = 0x05; //
            Send_buf[2] = 0x0A; //length
            switch (btnTmp.Name)
            {
                case "EE_GMA_KEY0":
                    {
                        Send_buf[3] = 0x00;
                    }
                    break;
                case "EE_GMA_KEY1":
                    {
                        Send_buf[3] = 0x01;
                    }
                    break;
                case "EE_GMA_KEY2":
                    {
                        Send_buf[3] = 0x02;
                    }
                    break;
                case "EE_GMA_KEY3":
                    {
                        Send_buf[3] = 0x03;
                    }
                    break;
                case "EE_GMA_KEY4":
                    {
                        Send_buf[3] = 0x04;
                    }
                    break;
                case "EE_GMA_KEY5":
                    {
                        Send_buf[3] = 0x05;
                    }
                    break;
                case "EE_GMA_KEY6":
                    {
                        Send_buf[3] = 0x06;
                    }
                    break;
                case "EE_GMA_KEY7":
                    {
                        Send_buf[3] = 0x07;
                    }
                    break;
                case "EE_GMA_KEY8":
                    {
                        Send_buf[3] = 0x08;
                    }
                    break;
                case "EE_GMA_KEY9":
                    {
                        Send_buf[3] = 0x09;
                    }
                    break;
                default:
                    break;
            }
            CRCData.CalculateCrc16(Send_buf, out Send_buf[13], out Send_buf[14]);
            try
            {
                comPort.Write(Send_buf, 0, 15);
            }
            catch
            {
                show_LOG_main_msg("串口有误，请检查", "错误");
            }
            T1.Enabled = false;
            T1.Interval = 500;
            T1.Enabled = true;
        }
        private void Send_CASDK_Measure_data(object sender, EventArgs e)
        {
            Button btnTmp = (Button)sender;
            Send_buf = new byte[15];
            Setting.TempRecord.cmdLen = 15; //
            btn_CAS200_Synt_Click(btn_CASDK_Measure, null);

            //CASDK_LUM, CASDK_x, CASDK_y
            Send_buf[0] = 0x90;
            Send_buf[1] = 0x05; //
            Send_buf[2] = 0x0A; //length
            Send_buf[3] = 0x0A;
            Send_buf[4] = (byte)((int)(CASDK_LUM * 10000) >> 16);
            Send_buf[5] = (byte)((int)(CASDK_LUM * 10000) >> 8);
            Send_buf[6] = (byte)((int)(CASDK_LUM * 10000));
            Send_buf[7] = (byte)((int)(CASDK_x * 100000) >> 16);
            Send_buf[8] = (byte)((int)(CASDK_x * 100000) >> 8);
            Send_buf[9] = (byte)((int)(CASDK_x * 100000));
            Send_buf[10] = (byte)((int)(CASDK_y * 100000) >> 16);
            Send_buf[11] = (byte)((int)(CASDK_y * 100000) >> 8);
            Send_buf[12] = (byte)((int)(CASDK_y * 100000));

            CRCData.CalculateCrc16(Send_buf, out Send_buf[13], out Send_buf[14]);
            try
            {
                comPort.Write(Send_buf, 0, 15);
            }
            catch
            {
                show_LOG_main_msg("串口有误，请检查", "错误");
            }
            T1.Enabled = false;
            T1.Interval = 500;
            T1.Enabled = true;
        }
        public void T20_Tick(object sender, EventArgs e)
        {
            //Gamma调试用，千万别改
        }

        private void RGBTimeingChanged(object sender, EventArgs e)
        {
            if (BridgeChipModel.SelectedIndex == 0)  //SSD2828
            { //SSD2828 
                HFP.Maximum = 255;
                HBP.Maximum = 255;
                VBP.Maximum = 255;
                VFP.Maximum = 255;
            }
            else //SSD2832
            {
                HFP.Maximum = 2888;
                HBP.Maximum = 2888;
                VBP.Maximum = 2888;
                VFP.Maximum = 2888;
            }
            Int32 mipiB1, mipiB2, mipiB3, mipiB4, mipiB5, mipiB6;
            Int32 VBPVT, VFPVT, HBPVT, HFPVT;
            VBPVT = (Int32)VBP.Value;
            VFPVT = (Int32)VFP.Value;
            HBPVT = (Int32)HBP.Value;
            HFPVT = (Int32)HFP.Value;
            //因上位机UI中的HFP/HBP发送至FPGA后 rgb Timing 模块中 HFP 设定会被-3，HBP会被+3（某种不能明说，不能轻易改动的bug导致）
            //故此处做一个修正，修正后的值被传递给SSD2828/32配置参数,以保持FPGA发出的信号和SSD2828/32设定相一致
            //同样的bug也导致FPGA中的VFP/VBP与上位机UI中值不同，此处VFP会被-1，VBP会被+1
            //-----------------------------------以上问题待陈锋、MJB空时再修复----------------------------------------------
            string strTmp, strLine; int i, tepindex;
            mipiB1 = (Int16)((VSA.Value * 256) + HSA.Value);
            mipiB2 = 0xffff & (((VBPVT) << 8) + (HBPVT & 0xFF));
            mipiB3 = 0xffff & (((VFPVT) << 8) + (HFPVT & 0xFF));

            mipiB4 = (Int16)(HACT.Value);
            mipiB5 = (Int16)(VACT.Value);
            mipiB6 = 0x1037;
            if ((lstMIPISSD.Items.Count > 0) && (chk2828Autoset.Checked))
            {
                for (tepindex = 0; tepindex < lstMIPISSD.Items.Count - 1; tepindex++)
                {
                    strTmp = lstMIPISSD.Items[tepindex].ToString().Substring(0, 7);
                    strTmp = strTmp.ToUpper();

                    i = strTmp.IndexOf("B1=");
                    if (i == 0)
                    {
                        lstMIPISSD.Items[tepindex] = lstMIPISSD.Items[tepindex].ToString().Substring(0, 3) + mipiB1.ToString("X4");
                    }
                    i = strTmp.IndexOf("B2=");
                    if (i == 0)
                    {
                        lstMIPISSD.Items[tepindex] = lstMIPISSD.Items[tepindex].ToString().Substring(0, 3) + mipiB2.ToString("X4");
                        if (BridgeChipModel.SelectedIndex == 1)  //SSD2832
                        {
                            if (lstMIPISSD.Items[tepindex + 1].ToString().Substring(0, 3) == "00=")
                            {
                                lstMIPISSD.Items[tepindex + 1] = "00=" + ((Int16)(((VBPVT) & 0xFF00) + ((HBPVT & 0xFF00) >> 8))).ToString("X4");
                            }
                            else
                            {
                                strLine = "00=" + ((Int16)(((VBPVT) & 0xFF00) + ((HBPVT & 0xFF00) >> 8))).ToString("X4");
                                lstMIPISSD.Items.Insert(tepindex + 1, strLine);
                            }
                        }
                    }
                    i = strTmp.IndexOf("B3=");
                    if (i == 0)
                    {
                        lstMIPISSD.Items[tepindex] = lstMIPISSD.Items[tepindex].ToString().Substring(0, 3) + mipiB3.ToString("X4");
                        if (BridgeChipModel.SelectedIndex == 1)  //SSD2832
                        {
                            if (lstMIPISSD.Items[tepindex + 1].ToString().Substring(0, 3) == "00=")
                            {
                                lstMIPISSD.Items[tepindex + 1] = "00=" + ((Int16)(((VFPVT) & 0xFF00) + ((HFPVT & 0xFF00) >> 8))).ToString("X4");
                            }
                            else
                            {
                                strLine = "00=" + ((Int16)(((VFPVT) & 0xFF00) + ((HFPVT & 0xFF00) >> 8))).ToString("X4");
                                lstMIPISSD.Items.Insert((tepindex + 1), strLine);
                            }
                        }
                    }
                    i = strTmp.IndexOf("B4=");
                    if (i == 0)
                    {
                        lstMIPISSD.Items[tepindex] = lstMIPISSD.Items[tepindex].ToString().Substring(0, 3) + mipiB4.ToString("X4");
                    }
                    i = strTmp.IndexOf("B5=");
                    if (i == 0)
                    {
                        lstMIPISSD.Items[tepindex] = lstMIPISSD.Items[tepindex].ToString().Substring(0, 3) + mipiB5.ToString("X4");
                    }
                    if (BridgeChipModel.SelectedIndex == 1)  //SSD2832 对应的B6 寄存器 ，酌情调整为1037 或者 1033 或者 10ab /10af
                    {
                        i = strTmp.IndexOf("B6=");
                        if (i == 0)
                        {
                            lstMIPISSD.Items[tepindex] = "B6=" + mipiB6.ToString("X4");
                        }
                    }
                }
            }
        }
        private void MipiClkValueChanged(object sender, EventArgs e)
        {
            UInt16 mipiBa, mipiBb, mipiDe, FR = 1;
            string strTmp;
            int i, tepindex;
            long mipiSpeedSet = (long)(numRegBA_NS.Value * 24) / (long)numRegBA_MS.Value;
            if (mipiSpeedSet > 501)
            { FR = 3; }
            else if (mipiSpeedSet > 251)
            { FR = 2; }
            else if (mipiSpeedSet > 126)
            { FR = 1; }
            else if (mipiSpeedSet > 62.5)
            { FR = 0; }
            else
            { textBox1.Text = "MIPI速度设置异常！\r\n"; }
            mipiBa = (UInt16)((FR << 14) + (numRegBA_MS.Value * 256) + numRegBA_NS.Value);
            mipiBb = (UInt16)(mipiSpeedSet / 68.0);
            mipiBb = (UInt16)(mipiBb & 0x00ff);
            byte mipilines = (byte)(numMipiLanCount.Value - 1);
            mipiDe = (UInt16)(mipilines << 2 | mipilines | 0x0070);
            if (mipiSpeedSet > mipiSpeedNeed)
            {
                labmipisetvalue.ForeColor = System.Drawing.Color.SeaGreen;
                labmipisetvalue.Text = "设定速度=" + mipiSpeedSet.ToString("f1") + " ;";                 //实际设定速度
            }
            else
            {
                labmipisetvalue.ForeColor = System.Drawing.Color.Red;
                labmipisetvalue.Text = "设定速度=" + mipiSpeedSet.ToString("f1") + " X";                 //实际设定速度
            }
            //labeMipiSpeed.Text = "mipi速度"+ mipiSpeedNeed.ToString("f1")+"M/s";                   //理论需求速度  
            if ((lstMIPISSD.Items.Count > 0))
            {
                for (tepindex = 0; tepindex < lstMIPISSD.Items.Count - 1; tepindex++)
                {
                    strTmp = lstMIPISSD.Items[tepindex].ToString().Substring(0, 7);
                    strTmp = strTmp.ToUpper();
                    i = strTmp.IndexOf("BA=");
                    if (i == 0)
                    {
                        lstMIPISSD.Items[tepindex] = lstMIPISSD.Items[tepindex].ToString().Substring(0, 3) + mipiBa.ToString("X4");
                    }
                    i = strTmp.IndexOf("BB=");
                    if (i == 0)
                    {
                        lstMIPISSD.Items[tepindex] = lstMIPISSD.Items[tepindex].ToString().Substring(0, 3) + mipiBb.ToString("X4");
                    }
                    i = strTmp.IndexOf("DE=");
                    if (i == 0)
                    {
                        lstMIPISSD.Items[tepindex] = lstMIPISSD.Items[tepindex].ToString().Substring(0, 3) + mipiDe.ToString("X4");
                    }
                }
            }
        }
        long mipiSpeedNeed;
        private void PclkValueChanged(object sender, EventArgs e)
        {
            mipiSpeedNeed = (long)(Pixel_Clock.Value * 24) / (long)numMipiLanCount.Value;
            labeMipiSpeed.Text = "mipi速度" + mipiSpeedNeed.ToString("f1") + "M/s";          //理论需求速度
            int i = (int)(Pixel_Clock.Value * 1000000 / (HACT.Value + HSA.Value + HBP.Value + HFP.Value) / (VACT.Value + VSA.Value + VBP.Value + VFP.Value));
            textBox1.Text += i + "\r\n";   //悄悄显示刷新频率
        }
        private void BridgeChipModel_SelectedIndexChanged(object sender, EventArgs e)
        {
            //   textBox1.Text += "使用2832 时需要注意 b6寄存器 ，酌情调整为1037 或者 1033 或者 10ab /10af" + "\r\n" +
            //      "0xDE寄存器也要相应调整为0x7F或0x3F" + "\r\n";
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("https://docs.qq.com/sheet/DSGlpSmJMUmx6TmFq");
        }

        private void chk2828Autoset_MouseEnter(object sender, EventArgs e)
        {
            ToolTip p = new ToolTip();
            p.ShowAlways = true;
            p.SetToolTip(this.chk2828Autoset, "SSD2828/32寄存器配置B1-B5会随着上面参数内容联动");
        }

        private void Generate_Key_Enable_Click(object sender, EventArgs e)
        {
            Generate_File_Run.Enabled = true;
        }

        Bitmap Zoom_img1;
        private void ZOOM_PIC_Load_Click(object sender, EventArgs e)
        {
            OpenFileDialog sf = new OpenFileDialog();
            sf.Filter = @"bmp图片(*.bmp)|*.bmp|所有文件(*.*)|*.*"; //定义文件的类型
            sf.Title = "图片导入";
            if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
            {
                FileStream fs = new FileStream(sf.FileName, FileMode.Open);
                tBx_ZOOM_PIC.Text = sf.FileName;
                Zoom_img1 = new Bitmap(fs);
                fs.Close();
            }
        }

        private void ZOOM_PIC_Convert_Click(object sender, EventArgs e)
        {
            Bitmap img2 = new Bitmap(Convert.ToInt32(ZOOM_PIC_H.Value), Convert.ToInt32(ZOOM_PIC_V.Value), PixelFormat.Format24bppRgb);
            img2.SetResolution(900.0F, 900.0F);
            using (Graphics g = Graphics.FromImage(img2))
            {
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.DrawImage(Zoom_img1, new Rectangle(0, 0, img2.Width, img2.Height), 0, 0, Zoom_img1.Width, Zoom_img1.Height, GraphicsUnit.Pixel);
                g.Dispose();
                img2.Save(tBx_ZOOM_PIC.Text, ImageFormat.Bmp);
                MessageBox.Show("转换完成！");
            }
        }

        private void update2k_ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://172.16.3.77:8080/2ksModuleDebug/");
            show_LOG_main_msg("在弹出浏览器页面中找到“Module_Debug.application”点击即可！", "暂时只支持内网");
        }

        private void btn_bistT_Click(object sender, EventArgs e)
        {//--临时测试，待CQ完善            
            //BistSend(false, 0xc0,1);
            //BistSend(true, 0x5004, 0x000000ff);//颜色-R
            //BistSend(true, 0x5008, 0x00ff00ff);//颜色-G-B
            //BistSend(true, 0x500c, 0x000000ff);//颜色-R
            //BistSend(true, 0x5010, 0x00ff00ff);//颜色-G-B
            //BistSend(true, 0x5014, 0x04370000);//X起始位置start-end
            //BistSend(true, 0x5018, 0x00010000);//y起始位置start-end
            //BistSend(true, 0x7fff, 0);
            //BistSend(true, 0x6fff, 0);cmdAddr地址为7fff时FPGA进入low；地址是6fff时FPGA重置（没实现功能），不影响其他bist图使用

        }
        private void BistSend(bool ApbFlag, UInt16 CmdAddr, UInt32 cmdParam)
        {//--临时测试，待CQ完善
            Send_buf = new byte[25];
            Setting.TempRecord.cmdLen = 10;
            Send_buf[0] = 0x0A;
            Send_buf[1] = 0xF9;
            Send_buf[2] = 21; //25-4
            if (ApbFlag)
                Send_buf[3] = 0x10;     //0x10 0x11:APB Write/read; 
            else
                Send_buf[3] = 0x00;     //0x00 0x01：Normar Write/ read

            Send_buf[4] = (byte)(CmdAddr >> 8);
            Send_buf[5] = (byte)(CmdAddr >> 0);
            Send_buf[6] = (byte)(cmdParam >> 24);
            Send_buf[7] = (byte)(cmdParam >> 16);
            Send_buf[8] = (byte)(cmdParam >> 8);
            Send_buf[9] = (byte)(cmdParam >> 0);

            CRCData.CalculateCrc16(Send_buf, out Send_buf[23], out Send_buf[24]);
            try
            {
                comPort.Write(Send_buf, 0, 25);
            }
            catch
            {
                show_LOG_main_msg("串口有误，请检查", "错误");
            }

            T1.Enabled = false;
            T1.Interval = 500;
            T1.Enabled = true;
        }

        private void tbx_2832bist_key_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < lstMIPISSD.Items.Count; i++)
            {
                lstMIPISSD.SelectedIndex = i;
                txtMIPISSD.Text = lstMIPISSD.Items[i].ToString();
                btnMipiSSDW_Click(btnMipiSSDW, e);
                Thread.Sleep(10);
            }
            flag_2832bist = false;
            BistSend(true, 0x6fff, 0);
        }
        bool flag_2832bist = false;//是否初次进入bist模式，专为V向渐变图加入，难受。
        private void button1_Click_1(object sender, EventArgs e)
        {
            UInt32 value_5004 = Convert.ToUInt32(nud_2832bist_R1.Value);
            UInt32 value_5008 = ((Convert.ToUInt32(nud_2832bist_G1.Value) << 16) + Convert.ToUInt32(nud_2832bist_B1.Value));
            UInt32 value_500C = Convert.ToUInt32(nud_2832bist_R2.Value);
            UInt32 value_5010 = ((Convert.ToUInt32(nud_2832bist_G2.Value) << 16) + Convert.ToUInt32(nud_2832bist_B2.Value));
            UInt32 value_5014 = ((Convert.ToUInt32(nud_2832bist_X_START.Value) << 16) + Convert.ToUInt32(nud_2832bist_X_END.Value));
            UInt32 value_5018 = ((Convert.ToUInt32(nud_2832bist_Y_START.Value) << 16) + Convert.ToUInt32(nud_2832bist_Y_END.Value));
            UInt32 value_5000 = Convert.ToUInt32(nud_2832bist_EN.Value) << 16;
            if (flag_2832bist == false)
            {
                BistSend(true, 0x7fff, 0);
            }

            switch (cbx_2832bist.SelectedIndex)
            {
                case 0://单色灰阶图
                    {
                        value_5000 = value_5000 + 0xf1;
                        BistSend(false, 0xc0, 1);
                        BistSend(false, 0xb7, 0);
                        BistSend(true, 0x5004, value_5004);//颜色-R
                        BistSend(true, 0x5008, value_5008);//颜色-G-B
                        BistSend(true, 0x5000, value_5000);//第一位是开关，第二位是mode；后面四位是细节设定，详情查手册
                        BistSend(false, 0xb7, 0x034b);
                        flag_2832bist = true;
                        break;
                    }
                case 1://循环color图，固定16张图循环，可设置循环间隔帧数，不可设置图片
                    {
                        value_5000 = value_5000 + 0x01;
                        BistSend(false, 0xc0, 1);
                        BistSend(true, 0x5000, value_5000);//第一位是开关，第二位是mode；后面四位是细节设定，详情查手册
                        Thread.Sleep(200);
                        flag_2832bist = true;
                        break;
                    }
                case 2://V向color渐变图，color不可设置，可以设置宽度，单位是pixel
                    {
                        value_5000 = value_5000 + 0x11;
                        if (flag_2832bist)
                        {
                            BistSend(false, 0xc0, 1);
                            BistSend(true, 0x5000, value_5000);//第一位是开关，第二位是mode；后面四位是细节设定，详情查手册
                        }
                        else
                        {
                            BistSend(false, 0xb7, 0);
                            BistSend(true, 0x5000, value_5000);//第一位是开关，第二位是mode；后面四位是细节设定，详情查手册
                            BistSend(false, 0xb7, 0x034b);
                        }
                        flag_2832bist = true;
                        break;
                    }
                case 3://H向color渐变图，color不可设置，可以设置宽度，单位是pixel
                    {
                        value_5000 = value_5000 + 0x21;
                        BistSend(false, 0xc0, 1);
                        BistSend(false, 0xb7, 0);
                        BistSend(true, 0x5000, value_5000);//第一位是开关，第二位是mode；后面四位是细节设定，详情查手册
                        BistSend(false, 0xb7, 0x034b);
                        flag_2832bist = true;
                        break;
                    }
                case 4://棋盘格
                    {
                        value_5000 = value_5000 + 0x31;
                        BistSend(false, 0xc0, 1);
                        if (flag_2832bist)
                        {
                            BistSend(true, 0x5004, value_5004);//颜色-R
                            BistSend(true, 0x5008, value_5008);//颜色-G-B
                            BistSend(true, 0x500c, value_500C);//颜色-R
                            BistSend(true, 0x5010, value_5010);//颜色-G-B
                            BistSend(true, 0x5000, value_5000);//第一位是开关，第二位是mode；后面四位是细节设定，详情查手册
                        }
                        else
                        {
                            BistSend(false, 0xb7, 0);
                            BistSend(true, 0x5004, value_5004);//颜色-R
                            BistSend(true, 0x5008, value_5008);//颜色-G-B
                            BistSend(true, 0x500c, value_500C);//颜色-R
                            BistSend(true, 0x5010, value_5010);//颜色-G-B
                            BistSend(true, 0x5000, value_5000);//第一位是开关，第二位是mode；后面四位是细节设定，详情查手册
                            BistSend(false, 0xb7, 0x034b);
                        }

                        flag_2832bist = true;
                        break;
                    }
                case 5://H向灰阶渐变图
                case 6://V向灰阶渐变图
                    {
                        if (nud_2832bist_EN.Value % 4 != 0)
                        {
                            int a = Convert.ToInt16(nud_2832bist_EN.Value);
                            a = a / 4 * 4;
                            nud_2832bist_EN.Value = a;
                            MessageBox.Show("H向渐变图宽度必须设置为4的整数倍");
                        }
                        value_5000 = Convert.ToUInt32(nud_2832bist_EN.Value) << 16;
                        if (cbx_2832bist.SelectedIndex == 5)
                        {
                            value_5000 = value_5000 + 0x41;
                        }
                        else
                        {
                            value_5000 = value_5000 + 0x51;
                        }
                        BistSend(false, 0xc0, 1);
                        if (flag_2832bist)
                        {
                            BistSend(true, 0x5004, value_5004);//颜色-R-起始颜色
                            BistSend(true, 0x5008, value_5008);//颜色-G-B
                            BistSend(true, 0x500c, value_500C);//颜色-R-每个步进的灰阶增加量
                            BistSend(true, 0x5010, value_5010);//颜色-G-B
                            BistSend(true, 0x5000, value_5000);//pixels for each color step
                        }
                        else
                        {
                            BistSend(false, 0xb7, 0);
                            BistSend(true, 0x5004, value_5004);//颜色-R-起始颜色
                            BistSend(true, 0x5008, value_5008);//颜色-G-B
                            BistSend(true, 0x500c, value_500C);//颜色-R-每个步进的灰阶增加量
                            BistSend(true, 0x5010, value_5010);//颜色-G-B
                            BistSend(true, 0x5000, value_5000);//pixels for each color step
                            BistSend(false, 0xb7, 0x034b);
                        }
                        flag_2832bist = true;
                        break;
                    }
                case 7://实心填充矩形可配置的位置
                    {
                        value_5000 = value_5000 + 0x61;
                        if (nud_2832bist_X_START.Value % 4 != 0)
                        {
                            int a = Convert.ToInt16(nud_2832bist_X_START.Value);
                            a = a / 4 * 4;
                            nud_2832bist_X_START.Value = a;
                            MessageBox.Show("H向宽度必须设置为4的整数倍");
                        }
                        if (nud_2832bist_X_END.Value % 4 != 0)
                        {
                            int a = Convert.ToInt16(nud_2832bist_X_END.Value);
                            a = a / 4 * 4;
                            nud_2832bist_X_END.Value = a;
                            MessageBox.Show("H向宽度必须设置为4的整数倍");
                        }
                        value_5014 = ((Convert.ToUInt32(nud_2832bist_X_START.Value) << 16) + Convert.ToUInt32(nud_2832bist_X_END.Value));
                        value_5018 = ((Convert.ToUInt32(nud_2832bist_Y_START.Value) << 16) + Convert.ToUInt32(nud_2832bist_Y_END.Value));
                        BistSend(false, 0xc0, 1);
                        if (flag_2832bist)
                        {
                            BistSend(true, 0x5004, value_5004);//颜色-R-前景色
                            BistSend(true, 0x5008, value_5008);//颜色-G-B-前景色
                            BistSend(true, 0x500c, value_500C);//颜色-R-背景色
                            BistSend(true, 0x5010, value_5010);//颜色-G-B-背景色
                            BistSend(true, 0x5014, value_5014);//横向起始位置和结束位置
                            BistSend(true, 0x5018, value_5018);//纵向起始位置和结束位置
                            BistSend(true, 0x5000, value_5000);
                        }
                        else
                        {
                            BistSend(false, 0xb7, 0);
                            BistSend(true, 0x5004, value_5004);//颜色-R-前景色
                            BistSend(true, 0x5008, value_5008);//颜色-G-B-前景色
                            BistSend(true, 0x500c, value_500C);//颜色-R-背景色
                            BistSend(true, 0x5010, value_5010);//颜色-G-B-背景色
                            BistSend(true, 0x5014, value_5014);//横向起始位置和结束位置
                            BistSend(true, 0x5018, value_5018);//纵向起始位置和结束位置
                            BistSend(true, 0x5000, value_5000);
                            BistSend(false, 0xb7, 0x034b);
                        }
                        flag_2832bist = true;
                        break;
                    }
                case 8://边框图
                    {
                        value_5000 = value_5000 + 0x71;
                        BistSend(false, 0xc0, 1);
                        if (flag_2832bist)
                        {
                            BistSend(true, 0x5004, value_5004);//颜色-R-前景色
                            BistSend(true, 0x5008, value_5008);//颜色-G-B-前景色
                            BistSend(true, 0x500c, value_500C);//颜色-R-背景色
                            BistSend(true, 0x5010, value_5010);//颜色-G-B-背景色
                            BistSend(true, 0x5000, value_5000);
                        }
                        else
                        {
                            BistSend(false, 0xb7, 0);
                            BistSend(true, 0x5004, value_5004);//颜色-R-前景色
                            BistSend(true, 0x5008, value_5008);//颜色-G-B-前景色
                            BistSend(true, 0x500c, value_500C);//颜色-R-背景色
                            BistSend(true, 0x5010, value_5010);//颜色-G-B-背景色
                            BistSend(true, 0x5000, value_5000);
                            BistSend(false, 0xb7, 0x034b);
                        }
                        flag_2832bist = true;
                        break;
                    }
                case 9://V向交替颜色图，宽度为1个pixel
                case 10://H向交替颜色图，宽度为1个pixel
                    {

                        if (cbx_2832bist.SelectedIndex == 9)
                        {
                            value_5000 = value_5000 + 0x81;
                        }
                        else
                        {
                            value_5000 = value_5000 + 0x91;
                        }
                        BistSend(false, 0xc0, 1);
                        if (flag_2832bist)
                        {
                            BistSend(true, 0x5004, value_5004);//颜色-R-color1
                            BistSend(true, 0x5008, value_5008);//颜色-G-B-color1
                            BistSend(true, 0x500c, value_500C);//颜色-R-color2
                            BistSend(true, 0x5010, value_5010);//颜色-G-B-color2
                            BistSend(true, 0x5000, value_5000);
                        }
                        else
                        {
                            BistSend(false, 0xb7, 0);
                            BistSend(true, 0x5004, value_5004);//颜色-R-color1
                            BistSend(true, 0x5008, value_5008);//颜色-G-B-color1
                            BistSend(true, 0x500c, value_500C);//颜色-R-color2
                            BistSend(true, 0x5010, value_5010);//颜色-G-B-color2
                            BistSend(true, 0x5000, value_5000);
                            BistSend(false, 0xb7, 0x034b);
                        }
                        flag_2832bist = true;
                        break;
                    }
                case 11://十字光标线，宽度为1个pixel
                    {
                        value_5000 = value_5000 + 0xA1;
                        BistSend(false, 0xc0, 1);
                        if (flag_2832bist)
                        {
                            BistSend(true, 0x5004, value_5004);//颜色-R-color1
                            BistSend(true, 0x5008, value_5008);//颜色-G-B-color1
                            BistSend(true, 0x500c, value_500C);//颜色-R-color2
                            BistSend(true, 0x5010, value_5010);//颜色-G-B-color2
                            BistSend(true, 0x5014, value_5014);//横向起始位置
                            BistSend(true, 0x5018, value_5018);//纵向起始位置
                            BistSend(true, 0x5000, value_5000);
                        }
                        else
                        {
                            BistSend(false, 0xb7, 0);
                            BistSend(true, 0x5004, value_5004);//颜色-R-color1
                            BistSend(true, 0x5008, value_5008);//颜色-G-B-color1
                            BistSend(true, 0x500c, value_500C);//颜色-R-color2
                            BistSend(true, 0x5010, value_5010);//颜色-G-B-color2
                            BistSend(true, 0x5014, value_5014);//横向起始位置
                            BistSend(true, 0x5018, value_5018);//纵向起始位置
                            BistSend(true, 0x5000, value_5000);
                            BistSend(false, 0xb7, 0x034b);
                        }
                        flag_2832bist = true;
                        break;
                    }
                case 12:////像素偏移图...不知道有啥用，en的值用于设置每隔多少行变换一次；Y_START用于设置起始行的位置；
                    {
                        value_5000 = value_5000 + 0xC1;
                        BistSend(false, 0xc0, 1);
                        if (flag_2832bist)
                        {
                            BistSend(true, 0x5004, value_5004);//颜色-R-color1
                            BistSend(true, 0x5008, value_5008);//颜色-G-B-color1
                            BistSend(true, 0x500c, value_500C);//颜色-R-color2
                            BistSend(true, 0x5010, value_5010);//颜色-G-B-color2
                            BistSend(true, 0x5014, value_5014);//横向起始位置
                            BistSend(true, 0x5018, value_5018);//纵向起始位置
                            BistSend(true, 0x5000, value_5000);
                        }
                        else
                        {
                            BistSend(false, 0xb7, 0);
                            BistSend(true, 0x5004, value_5004);//颜色-R-color1
                            BistSend(true, 0x5008, value_5008);//颜色-G-B-color1
                            BistSend(true, 0x500c, value_500C);//颜色-R-color2
                            BistSend(true, 0x5010, value_5010);//颜色-G-B-color2
                            BistSend(true, 0x5014, value_5014);//横向起始位置
                            BistSend(true, 0x5018, value_5018);//纵向起始位置
                            BistSend(true, 0x5000, value_5000);
                            BistSend(false, 0xb7, 0x034b);
                        }
                        flag_2832bist = true;
                        break;
                    }
                case 13://动图，在背景图上有一条竖带移动
                case 14://动图，在背景图上有一条横带移动
                    {
                        if (cbx_2832bist.SelectedIndex == 13)
                        {
                            value_5000 = value_5000 + 0xD1;
                        }
                        else
                        {
                            value_5000 = value_5000 + 0xE1;
                        }
                        if (nud_2832bist_X_START.Value % 4 != 0)
                        {
                            int a = Convert.ToInt16(nud_2832bist_X_START.Value);
                            a = a / 4 * 4;
                            nud_2832bist_X_START.Value = a;
                            MessageBox.Show("H_START必须设置为4的整数倍");
                        }
                        if (nud_2832bist_X_END.Value % 4 != 0)
                        {
                            int a = Convert.ToInt16(nud_2832bist_X_END.Value);
                            a = a / 4 * 4;
                            nud_2832bist_X_END.Value = a;
                            MessageBox.Show("H_END必须设置为4的整数倍");
                        }
                        value_5014 = ((Convert.ToUInt32(nud_2832bist_X_START.Value) << 16) + Convert.ToUInt32(nud_2832bist_X_END.Value));
                        value_5018 = ((Convert.ToUInt32(nud_2832bist_Y_START.Value) << 16) + Convert.ToUInt32(nud_2832bist_Y_END.Value));
                        BistSend(false, 0xc0, 1);
                        if (flag_2832bist)
                        {
                            BistSend(true, 0x5004, value_5004);//颜色-R-color1
                            BistSend(true, 0x5008, value_5008);//颜色-G-B-color1
                            BistSend(true, 0x500c, value_500C);//颜色-R-color2
                            BistSend(true, 0x5010, value_5010);//颜色-G-B-color2
                            BistSend(true, 0x5014, value_5014);//横向起始位置和结束位置
                            BistSend(true, 0x5018, value_5018);//纵向起始位置和结束位置
                            BistSend(true, 0x5000, value_5000);
                        }
                        else
                        {
                            BistSend(false, 0xb7, 0);
                            BistSend(true, 0x5004, value_5004);//颜色-R-color1
                            BistSend(true, 0x5008, value_5008);//颜色-G-B-color1
                            BistSend(true, 0x500c, value_500C);//颜色-R-color2
                            BistSend(true, 0x5010, value_5010);//颜色-G-B-color2
                            BistSend(true, 0x5014, value_5014);//横向起始位置和结束位置
                            BistSend(true, 0x5018, value_5018);//纵向起始位置和结束位置
                            BistSend(true, 0x5000, value_5000);
                            Thread.Sleep(200);
                            BistSend(false, 0xb7, 0x034b);
                        }
                        flag_2832bist = true;
                        break;
                    }


            }
        }

        private void cbx_2832bist_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (cbx_2832bist.SelectedIndex)
            {
                case 0://单色图
                    {
                        nud_2832bist_EN.Enabled = false;

                        nud_2832bist_B2.Enabled = false;
                        nud_2832bist_G2.Enabled = false;
                        nud_2832bist_R2.Enabled = false;

                        nud_2832bist_B1.Enabled = true;
                        nud_2832bist_G1.Enabled = true;
                        nud_2832bist_R1.Enabled = true;

                        nud_2832bist_X_END.Enabled = false;
                        nud_2832bist_X_START.Enabled = false;
                        nud_2832bist_Y_END.Enabled = false;
                        nud_2832bist_Y_START.Enabled = false;

                        lab_2832bist_EN.Text = "not used:";
                        break;
                    }
                case 1://循环color图，固定16张图循环，可设置循环间隔帧数，不可设置图片
                    {
                        nud_2832bist_EN.Enabled = true;
                        nud_2832bist_EN.Value = 8;

                        nud_2832bist_B2.Enabled = false;
                        nud_2832bist_G2.Enabled = false;
                        nud_2832bist_R2.Enabled = false;

                        nud_2832bist_B1.Enabled = false;
                        nud_2832bist_G1.Enabled = false;
                        nud_2832bist_R1.Enabled = false;

                        nud_2832bist_X_END.Enabled = false;
                        nud_2832bist_X_START.Enabled = false;
                        nud_2832bist_Y_END.Enabled = false;
                        nud_2832bist_Y_START.Enabled = false;
                        lab_2832bist_EN.Text = "间隔帧数:";
                        break;
                    }
                case 2://V向color渐变图，color不可设置，可以设置宽度，单位是pixel
                case 3://H向color渐变图，color不可设置，可以设置宽度，单位是pixel
                    {
                        nud_2832bist_EN.Enabled = true;
                        nud_2832bist_EN.Value = 80;

                        nud_2832bist_B2.Enabled = false;
                        nud_2832bist_G2.Enabled = false;
                        nud_2832bist_R2.Enabled = false;

                        nud_2832bist_B1.Enabled = false;
                        nud_2832bist_G1.Enabled = false;
                        nud_2832bist_R1.Enabled = false;

                        nud_2832bist_X_END.Enabled = false;
                        nud_2832bist_X_START.Enabled = false;
                        nud_2832bist_Y_END.Enabled = false;
                        nud_2832bist_Y_START.Enabled = false;
                        lab_2832bist_EN.Text = "Color bar width in pixels:";
                        break;
                    }
                case 4://棋盘格
                    {
                        nud_2832bist_EN.Enabled = true;
                        nud_2832bist_EN.Value = 80;

                        nud_2832bist_B2.Enabled = true;
                        nud_2832bist_G2.Enabled = true;
                        nud_2832bist_R2.Enabled = true;

                        nud_2832bist_B1.Enabled = true;
                        nud_2832bist_G1.Enabled = true;
                        nud_2832bist_R1.Enabled = true;

                        nud_2832bist_X_END.Enabled = false;
                        nud_2832bist_X_START.Enabled = false;
                        nud_2832bist_Y_END.Enabled = false;
                        nud_2832bist_Y_START.Enabled = false;
                        lab_2832bist_EN.Text = "棋盘格宽度:";
                        break;
                    }
                case 5://H向灰阶渐变图
                case 6://V向灰阶渐变图
                    {
                        nud_2832bist_EN.Enabled = true;
                        nud_2832bist_EN.Value = 80;

                        nud_2832bist_B2.Enabled = true;
                        nud_2832bist_G2.Enabled = true;
                        nud_2832bist_R2.Enabled = true;

                        nud_2832bist_B1.Enabled = true;
                        nud_2832bist_G1.Enabled = true;
                        nud_2832bist_R1.Enabled = true;

                        nud_2832bist_X_END.Enabled = false;
                        nud_2832bist_X_START.Enabled = false;
                        nud_2832bist_Y_END.Enabled = false;
                        nud_2832bist_Y_START.Enabled = false;
                        lab_2832bist_EN.Text = "每阶宽度:";
                        groupBox22.Text = "每阶变量";
                        groupBox23.Text = "起始颜色";
                        break;
                    }
                case 7://实心填充矩形可配置的位置
                    {
                        nud_2832bist_EN.Enabled = false;
                        nud_2832bist_EN.Value = 80;

                        nud_2832bist_B2.Enabled = true;
                        nud_2832bist_G2.Enabled = true;
                        nud_2832bist_R2.Enabled = true;

                        nud_2832bist_B1.Enabled = true;
                        nud_2832bist_G1.Enabled = true;
                        nud_2832bist_R1.Enabled = true;

                        nud_2832bist_X_END.Enabled = true;
                        nud_2832bist_X_START.Enabled = true;
                        nud_2832bist_Y_END.Enabled = true;
                        nud_2832bist_Y_START.Enabled = true;
                        lab_2832bist_EN.Text = "not used:";
                        groupBox23.Text = "局部色";
                        groupBox22.Text = "底色";
                        break;
                    }
                case 8://边框图
                    {
                        nud_2832bist_EN.Enabled = true;
                        nud_2832bist_EN.Value = 5;

                        nud_2832bist_B2.Enabled = true;
                        nud_2832bist_G2.Enabled = true;
                        nud_2832bist_R2.Enabled = true;

                        nud_2832bist_B1.Enabled = true;
                        nud_2832bist_G1.Enabled = true;
                        nud_2832bist_R1.Enabled = true;

                        nud_2832bist_X_END.Enabled = false;
                        nud_2832bist_X_START.Enabled = false;
                        nud_2832bist_Y_END.Enabled = false;
                        nud_2832bist_Y_START.Enabled = false;
                        lab_2832bist_EN.Text = "type:";
                        groupBox23.Text = "局部色";
                        groupBox22.Text = "底色";
                        break;
                    }
                case 9://V向交替颜色图，宽度为1个pixel
                case 10://H向交替颜色图，宽度为1个pixel
                    {
                        nud_2832bist_EN.Enabled = false;
                        nud_2832bist_EN.Value = 0;

                        nud_2832bist_B2.Enabled = true;
                        nud_2832bist_G2.Enabled = true;
                        nud_2832bist_R2.Enabled = true;

                        nud_2832bist_B1.Enabled = true;
                        nud_2832bist_G1.Enabled = true;
                        nud_2832bist_R1.Enabled = true;

                        nud_2832bist_X_END.Enabled = false;
                        nud_2832bist_X_START.Enabled = false;
                        nud_2832bist_Y_END.Enabled = false;
                        nud_2832bist_Y_START.Enabled = false;
                        lab_2832bist_EN.Text = "not used:";
                        groupBox23.Text = "color1";
                        groupBox22.Text = "color2";
                        break;
                    }
                case 11://十字光标线，宽度为1个pixel
                    {
                        nud_2832bist_EN.Enabled = false;
                        nud_2832bist_EN.Value = 0;

                        nud_2832bist_B2.Enabled = true;
                        nud_2832bist_G2.Enabled = true;
                        nud_2832bist_R2.Enabled = true;

                        nud_2832bist_B1.Enabled = true;
                        nud_2832bist_G1.Enabled = true;
                        nud_2832bist_R1.Enabled = true;

                        nud_2832bist_X_END.Enabled = false;
                        nud_2832bist_X_START.Enabled = true;
                        nud_2832bist_Y_END.Enabled = false;
                        nud_2832bist_Y_START.Enabled = true;
                        lab_2832bist_EN.Text = "not used:";
                        groupBox23.Text = "局部色";
                        groupBox22.Text = "底色";
                        break;
                    }
                case 12://像素偏移图...不知道有啥用，en的值用于设置每隔多少行变换一次；Y_START用于设置起始行的位置；
                    {
                        nud_2832bist_EN.Enabled = true;
                        nud_2832bist_EN.Value = 40;

                        nud_2832bist_B2.Enabled = true;
                        nud_2832bist_G2.Enabled = true;
                        nud_2832bist_R2.Enabled = true;

                        nud_2832bist_B1.Enabled = true;
                        nud_2832bist_G1.Enabled = true;
                        nud_2832bist_R1.Enabled = true;

                        nud_2832bist_X_END.Enabled = false;
                        nud_2832bist_X_START.Enabled = false;
                        nud_2832bist_Y_END.Enabled = false;
                        nud_2832bist_Y_START.Enabled = true;
                        lab_2832bist_EN.Text = "不懂:";
                        groupBox23.Text = "color1";
                        groupBox22.Text = "color2";
                        break;
                    }
                case 13://动图，在背景图上有一条竖带移动
                case 14://动图，在背景图上有一条横带移动
                    {
                        nud_2832bist_EN.Enabled = true;
                        nud_2832bist_EN.Value = 40;

                        nud_2832bist_B2.Enabled = true;
                        nud_2832bist_G2.Enabled = true;
                        nud_2832bist_R2.Enabled = true;

                        nud_2832bist_B1.Enabled = true;
                        nud_2832bist_G1.Enabled = true;
                        nud_2832bist_R1.Enabled = true;

                        nud_2832bist_X_END.Enabled = true;
                        nud_2832bist_X_START.Enabled = true;
                        nud_2832bist_Y_END.Enabled = true;
                        nud_2832bist_Y_START.Enabled = true;
                        lab_2832bist_EN.Text = "间隔帧数:";
                        groupBox23.Text = "局部色";
                        groupBox22.Text = "底色";
                        break;
                    }
            }
            if (cbx_2832bist.SelectedIndex == 13 || cbx_2832bist.SelectedIndex == 14)
            {
                label80.Text = "Move step:";
                label83.Text = "Bar width:";
                label81.Text = "Move step:";
                label78.Text = "Bar width:";
            }
            else
            {
                label80.Text = "X_START:";
                label83.Text = "X_END:";
                label81.Text = "Y_START:";
                label78.Text = "Y_END:";
            }
        }
        private void Gen_RGB_Bar_Scroll(object sender, EventArgs e)
        {
            Send_buf = new byte[25];
            //Button btnTmp = (Button)sender;
            Setting.TempRecord.cmdLen = 25;
            Send_buf[0] = 0x0A; //LCD配置标志
            Send_buf[2] = 0x15; //数据长度
            if (!this.comPort.IsOpen)
            {
                try
                {
                    comPort.PortName = Detection.GetComNum();
                    comPort.BaudRate = Setting.ComSet.comBaudRate;
                    this.openSerialPort(true);
                }
                catch
                {
                    show_LOG_main_msg("没有搜索到串口！", "错误提示");
                }
            }
            Gen_RGB.Text = Gen_RGB_Bar.Value.ToString();
            Send_buf[1] = 0x07;
            Send_buf[3] = cBx_Gen_R.Checked == true ? (byte)(Gen_RGB_Bar.Value) : (byte)(0);
            Send_buf[4] = cBx_Gen_G.Checked == true ? (byte)(Gen_RGB_Bar.Value) : (byte)(0);
            Send_buf[5] = cBx_Gen_B.Checked == true ? (byte)(Gen_RGB_Bar.Value) : (byte)(0);

            CRCData.CalculateCrc16(Send_buf, out Send_buf[23], out Send_buf[24]);
            try
            {
                comPort.Write(Send_buf, 0, 25);
            }
            catch
            {
                show_LOG_main_msg("串口有误，请检查", "错误");
            }
        }

        private void btn_Gen_RGB_Click(object sender, EventArgs e)
        {
            Gen_RGB_Bar.Value = (int)Gen_RGB.Value;
            Gen_RGB_Bar_Scroll(null, null);
        }
        private void swUpdate_Click(object sender, EventArgs e)
        {
            if (sender == null)
            {
                //Int32 days = DateTime.Now.Day;
                Int32 hours = DateTime.Now.Hour;
                if (hours % 2 == 0) return;   //减少更新次数；
            }
            string line1, res, res1;
            WebClient client = new WebClient();
            try
            {
                byte[] buffer = client.DownloadData("https://gitee.com/hufz/s2K_PCsw/raw/master/UpdateAddr.txt");
                //此处buffer 内不包含回车符号
                res = Encoding.UTF8.GetString(buffer);
                System.IO.StringReader reader = new System.IO.StringReader(res);

                byte[] buffer1 = client.DownloadData("https://gitee.com/hufz/s2K_PCsw/raw/master/notice.txt");
                res1 = Encoding.UTF8.GetString(buffer1);
                System.IO.StringReader reader1 = new System.IO.StringReader(res1);

                string[] linex = new string[System.Text.RegularExpressions.Regex.Matches(res, "\n").Count + 1];
                for (int tt = 0; tt < linex.Length; tt++)
                {
                    linex[tt] = reader.ReadLine();
                }
                toolStripStatusLabel_Tips.Text = "Ver:" + linex[3] + "更新地址：" + linex[1];
                textBox1.Text = "Ver:" + linex[3] + "\r\n";
                textBox1.Text += "上位机更新地址：" + "\r\n" + linex[1] + "\r\n" + "----------------------\r\n";
                //--------------------------------
                txtNotice.Clear();
                line1 = reader1.ReadLine();
                while (line1 != null)
                {
                    txtNotice.Text += line1 + "\r\n";
                    line1 = reader1.ReadLine();
                }
            }
            catch
            {
                textBox1.Text = "获取服务器信息失败\r\n请手动点击‘其他’选项卡里面的更新按钮，以查看版本信息";
            }
        }

        private void btn_Gen_TEST0_Click(object sender, EventArgs e)
        {
            txtCmd8.Text = "F0,AA,17\r\n";
            txtCmd8.Text = txtCmd8.Text + "BB," + ((byte)Gen_Test0.Value).ToString("x") + "," + ((byte)Gen_Test0.Value).ToString("x") + "," + ((byte)Gen_Test0.Value).ToString("x") + "," + ((byte)Gen_Test0.Value).ToString("x") + "," + ((byte)Gen_Test0.Value).ToString("x") + "," + ((byte)Gen_Test0.Value).ToString("x") + "," + ((byte)Gen_Test0.Value).ToString("x") + "," + ((byte)Gen_Test0.Value).ToString("x") + "," + "00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00\r\n";
            txtCmd8.Text = txtCmd8.Text + "BC," + ((byte)Gen_Test0.Value).ToString("x") + "," + ((byte)Gen_Test0.Value).ToString("x") + "," + ((byte)Gen_Test0.Value).ToString("x") + "," + ((byte)Gen_Test0.Value).ToString("x") + "," + ((byte)Gen_Test0.Value).ToString("x") + "," + ((byte)Gen_Test0.Value).ToString("x") + "," + ((byte)Gen_Test0.Value).ToString("x") + "," + ((byte)Gen_Test0.Value).ToString("x") + "," + "00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00\r\n";
            txtCmd8.Text = txtCmd8.Text + "BD," + ((byte)Gen_Test0.Value).ToString("x") + "," + ((byte)Gen_Test0.Value).ToString("x") + "," + ((byte)Gen_Test0.Value).ToString("x") + "," + ((byte)Gen_Test0.Value).ToString("x") + "," + ((byte)Gen_Test0.Value).ToString("x") + "," + ((byte)Gen_Test0.Value).ToString("x") + "," + ((byte)Gen_Test0.Value).ToString("x") + "," + ((byte)Gen_Test0.Value).ToString("x") + "," + "00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00\r\n";
            // BB,22,22,22,22,22,22,22,22,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00
            // BC,22,22,22,22,22,22,22,22,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00
            // BD,22,22,22,22,22,22,22,22,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00
            Send_Cmd_Click(btnSend8, null);
        }

        private void Gen_Test0_ValueChanged(object sender, EventArgs e)
        {
            btn_Gen_TEST0_Click(null, null);
        }

        private byte Dither_index = 1;
        private byte Dither_Start = 0;
        private void Tim_Dither_Tick(object sender, EventArgs e)
        {
            Tim_Dither.Stop();
            if (Dither_index == 1)
            {
                OLED_Show_Click(btnNextPic, null);
                if (!ComportWriteFlag)   //执行失败
                {
                    Tim_Dither.Stop();
                    return;
                }
                Dither_index = 0;
            }
            else
            {
                OLED_Show_Click(btnPrevPic, null);
                if (!ComportWriteFlag)  //执行失败
                {
                    Tim_Dither.Stop();
                    return;
                }
                Dither_index = 1;
            }
            Tim_Dither.Start();
        }
        bool ComportWriteFlag = false;
        private void btn_Dither_Click(object sender, EventArgs e)
        {
            if (Dither_Start == 0)
            {
                Dither_Start = 1;
                btn_Dither.Text = "Stop";
                Tim_Dither.Start();
            }
            else
            {
                Dither_Start = 0;
                btn_Dither.Text = "Dither";
                Tim_Dither.Stop();
            }
        }


        [DllImport("VIRC.dll", CallingConvention = CallingConvention.StdCall)]
        private static extern int VIRC_Adjust(int overrate_value, double write_balance_r, double write_balance_g, double write_balance_b, double color_balance_r, double color_balance_g, double color_balance_b);
        private void btn_IRC_Listen_Click(object sender, EventArgs e)
        {
            int ret = 0;
            if (!File.Exists("E:\\ZY_inputData.txt"))
            {

                ret = VIRC_Adjust((int)(IRC_Overrate.Value), (double)(IRC_R_WB_Ratio.Value), (double)(IRC_G_WB_Ratio.Value), (double)(IRC_B_WB_Ratio.Value), (double)(IRC_R_CB_Ratio.Value), (double)(IRC_G_CB_Ratio.Value), (double)(IRC_B_CB_Ratio.Value));
                if (ret == -1)
                {
                    MessageBox.Show("dll 输入文件缺失！");
                }

                FileStream fs = new FileStream("E:\\ZY_inputData.txt", FileMode.Append);
                StreamWriter sw = new StreamWriter(fs, Encoding.Default);

                sw.WriteLine(IRC_R_L_Color.Value.ToString());
                sw.WriteLine(IRC_G_L_Color.Value.ToString());
                sw.WriteLine(IRC_B_L_Color.Value.ToString());
                sw.WriteLine(IRC_R_M_Color.Value.ToString());
                sw.WriteLine(IRC_G_M_Color.Value.ToString());
                sw.WriteLine(IRC_B_M_Color.Value.ToString());

                sw.WriteLine(IRC_R_L_Ratio.Value.ToString());
                sw.WriteLine((100 - IRC_R_L_Ratio.Value).ToString());

                sw.Close();
                fs.Close();

                Time_IRC.Interval = 400;
                Time_IRC.Enabled = true;
            }
        }

        private void Time_IRC_Tick(object sender, EventArgs e)
        {
            if (File.Exists("E:\\ZY_outputData.txt"))
            {
                //    Time_IRC.Enabled = false;
                string[] strArray = File.ReadAllLines("E:\\ZY_outputData.txt");
                HFZ_L_R.Value = byte.Parse(strArray[0]);
                HFZ_L_G.Value = byte.Parse(strArray[1]);
                HFZ_L_B.Value = byte.Parse(strArray[2]);
                HFZ_M_R.Value = byte.Parse(strArray[3]);
                HFZ_M_G.Value = byte.Parse(strArray[4]);
                HFZ_M_B.Value = byte.Parse(strArray[5]);
                HFZ_Ratio.Value = byte.Parse(strArray[6]);
                Application.DoEvents();
                File.Delete("E:\\ZY_outputData.txt");
                OLED_Show_Click(btnlogic_go, null);
                //     Time_IRC.Enabled = true;
            }
        }

        private void btn_IRC_Listen_Stop_Click(object sender, EventArgs e)
        {
            Time_IRC.Enabled = false;
        }

        private void btn_IRC_Origin_Pattern_Click(object sender, EventArgs e)
        {
            HFZ_M_R.Value = IRC_R_M_Color.Value;
            HFZ_M_G.Value = IRC_G_M_Color.Value;
            HFZ_M_B.Value = IRC_B_M_Color.Value;
            HFZ_L_R.Value = IRC_R_L_Color.Value;
            HFZ_L_G.Value = IRC_G_L_Color.Value;
            HFZ_L_B.Value = IRC_B_L_Color.Value;
            HFZ_Ratio.Value = IRC_R_L_Ratio.Value;
            Application.DoEvents();
            OLED_Show_Click(btnlogic_go, null);
        }

        private void btn_IRC_Delta_E_Click(object sender, EventArgs e)
        {
            Button btnTmp = (Button)sender;
            switch (btnTmp.Name)
            {
                case "IRC_Delta_E_1":
                    {
                        btn_CAS200_Synt_Click(btn_CAS200_Measure, null);
                        IRC_Delta_E_listView.Items[0].SubItems[1].Text = CASDK_LUM.ToString();
                        IRC_Delta_E_listView.Items[0].SubItems[2].Text = CASDK_x.ToString();
                        IRC_Delta_E_listView.Items[0].SubItems[3].Text = CASDK_y.ToString();
                    }
                    break;
                case "IRC_Delta_E_2":
                    {
                        btn_CAS200_Synt_Click(btn_CAS200_Measure, null);
                        IRC_Delta_E_listView.Items[1].SubItems[1].Text = CASDK_LUM.ToString();
                        IRC_Delta_E_listView.Items[1].SubItems[2].Text = CASDK_x.ToString();
                        IRC_Delta_E_listView.Items[1].SubItems[3].Text = CASDK_y.ToString();
                    }
                    break;
                case "IRC_Delta_E_3":
                    {
                        btn_CAS200_Synt_Click(btn_CAS200_Measure, null);
                        IRC_Delta_E_listView.Items[2].SubItems[1].Text = CASDK_LUM.ToString();
                        IRC_Delta_E_listView.Items[2].SubItems[2].Text = CASDK_x.ToString();
                        IRC_Delta_E_listView.Items[2].SubItems[3].Text = CASDK_y.ToString();
                    }
                    break;
                case "IRC_Delta_E_4":
                    {
                        btn_CAS200_Synt_Click(btn_CAS200_Measure, null);
                        IRC_Delta_E_listView.Items[3].SubItems[1].Text = CASDK_LUM.ToString();
                        IRC_Delta_E_listView.Items[3].SubItems[2].Text = CASDK_x.ToString();
                        IRC_Delta_E_listView.Items[3].SubItems[3].Text = CASDK_y.ToString();
                    }
                    break;
                case "IRC_Measure_Data_1":
                    {
                        btn_CAS200_Synt_Click(btn_CAS200_Measure, null);
                        IRC_Ratio_listView.Items[0].SubItems[1].Text = CASDK_LUM.ToString();
                        IRC_Ratio_listView.Items[0].SubItems[2].Text = CASDK_x.ToString();
                        IRC_Ratio_listView.Items[0].SubItems[3].Text = CASDK_y.ToString();
                    }
                    break;
                case "IRC_Measure_Data_2":
                    {
                        btn_CAS200_Synt_Click(btn_CAS200_Measure, null);
                        IRC_Ratio_listView.Items[1].SubItems[1].Text = CASDK_LUM.ToString();
                        IRC_Ratio_listView.Items[1].SubItems[2].Text = CASDK_x.ToString();
                        IRC_Ratio_listView.Items[1].SubItems[3].Text = CASDK_y.ToString();
                    }
                    break;
                case "IRC_Delta_E_Calu":
                    {
                        double[] Point_A = new double[7] { 0.008856, 7.787, 16, 116, 903.3, 500, 200 };
                        double[] Point_B = new double[7] { 0.008856, 7.787, 16, 116, 903.3, 500, 200 };
                        double lv_1 = double.Parse(IRC_Delta_E_listView.Items[0].SubItems[1].Text);
                        double lv_2 = double.Parse(IRC_Delta_E_listView.Items[1].SubItems[1].Text);
                        double lv_3 = double.Parse(IRC_Delta_E_listView.Items[2].SubItems[1].Text);
                        double lv_4 = double.Parse(IRC_Delta_E_listView.Items[3].SubItems[1].Text);

                        double x_1 = double.Parse(IRC_Delta_E_listView.Items[0].SubItems[2].Text);
                        double x_2 = double.Parse(IRC_Delta_E_listView.Items[1].SubItems[2].Text);
                        double x_3 = double.Parse(IRC_Delta_E_listView.Items[2].SubItems[2].Text);
                        double x_4 = double.Parse(IRC_Delta_E_listView.Items[3].SubItems[2].Text);

                        double y_1 = double.Parse(IRC_Delta_E_listView.Items[0].SubItems[3].Text);
                        double y_2 = double.Parse(IRC_Delta_E_listView.Items[1].SubItems[3].Text);
                        double y_3 = double.Parse(IRC_Delta_E_listView.Items[2].SubItems[3].Text);
                        double y_4 = double.Parse(IRC_Delta_E_listView.Items[3].SubItems[3].Text);

                        double Y_1 = lv_1;
                        double X_1 = (x_1 / y_1) * Y_1;
                        double Z_1 = ((1 - x_1 - y_1) / y_1) * Y_1;

                        double Y_2 = lv_2;
                        double X_2 = (x_2 / y_2) * Y_2;
                        double Z_2 = ((1 - x_2 - y_2) / y_2) * Y_2;

                        double Y_3 = lv_3;
                        double X_3 = (x_3 / y_3) * Y_3;
                        double Z_3 = ((1 - x_3 - y_3) / y_3) * Y_3;

                        double Y_4 = lv_4;
                        double X_4 = (x_4 / y_4) * Y_4;
                        double Z_4 = ((1 - x_4 - y_4) / y_4) * Y_4;

                        double Xn_1 = 1;  //255 100%
                        double Yn_1 = 1;
                        double Zn_1 = 1;

                        double Xn_2 = 1; //255 %30
                        double Yn_2 = 1;
                        double Zn_2 = 1;

                        double Xn_3 = X_3 / X_1; //A
                        double Yn_3 = Y_3 / Y_1;
                        double Zn_3 = Z_3 / Z_1;

                        double Xn_4 = X_4 / X_2; //B
                        double Yn_4 = Y_4 / Y_2;
                        double Zn_4 = Z_4 / Z_2;

                        double fx1 = Xn_1 > Point_A[0] ? Math.Pow(Xn_1, (double)(1) / 3) : Point_A[1] * Xn_1 + Point_A[2] / Point_A[3];
                        double fy1 = Yn_1 > Point_A[0] ? Math.Pow(Yn_1, (double)(1) / 3) : Point_A[1] * Yn_1 + Point_A[2] / Point_A[3];
                        double fz1 = Zn_1 > Point_A[0] ? Math.Pow(Zn_1, (double)(1) / 3) : Point_A[1] * Zn_1 + Point_A[2] / Point_A[3]; //255 100%

                        double fx2 = Xn_2 > Point_B[0] ? Math.Pow(Xn_2, (double)(1) / 3) : Point_B[1] * Xn_2 + Point_B[2] / Point_B[3];
                        double fy2 = Yn_2 > Point_B[0] ? Math.Pow(Yn_2, (double)(1) / 3) : Point_B[1] * Yn_2 + Point_B[2] / Point_B[3];
                        double fz2 = Zn_2 > Point_B[0] ? Math.Pow(Zn_2, (double)(1) / 3) : Point_B[1] * Zn_2 + Point_B[2] / Point_B[3]; //255 30%

                        double fx3 = Xn_3 > Point_A[0] ? Math.Pow(Xn_3, (double)(1) / 3) : Point_A[1] * Xn_3 + Point_A[2] / Point_A[3];
                        double fy3 = Yn_3 > Point_A[0] ? Math.Pow(Yn_3, (double)(1) / 3) : Point_A[1] * Yn_3 + Point_A[2] / Point_A[3];
                        double fz3 = Zn_3 > Point_A[0] ? Math.Pow(Zn_3, (double)(1) / 3) : Point_A[1] * Zn_3 + Point_A[2] / Point_A[3]; //128 100%

                        double fx4 = Xn_4 > Point_B[0] ? Math.Pow(Xn_4, (double)(1) / 3) : Point_B[1] * Xn_4 + Point_B[2] / Point_B[3];
                        double fy4 = Yn_4 > Point_B[0] ? Math.Pow(Yn_4, (double)(1) / 3) : Point_B[1] * Yn_4 + Point_B[2] / Point_B[3];
                        double fz4 = Zn_4 > Point_B[0] ? Math.Pow(Zn_4, (double)(1) / 3) : Point_B[1] * Zn_4 + Point_B[2] / Point_B[3]; //128 30%

                        double L1 = Yn_1 > Point_A[0] ? (Point_A[3] * Math.Pow(Yn_1, (double)(1) / 3) - Point_A[2]) : (Point_A[4] * Yn_1);
                        L1 = L1 > 0 ? L1 : 0;
                        double a1 = Point_A[5] * (fx1 - fy1);
                        double b1 = Point_A[6] * (fy1 - fz1); //255 100%

                        double L2 = Yn_2 > Point_B[0] ? (Point_B[3] * Math.Pow(Yn_2, (double)(1) / 3) - Point_B[2]) : (Point_B[4] * Yn_2);
                        L2 = L2 > 0 ? L2 : 0;
                        double a2 = Point_B[5] * (fx2 - fy2);
                        double b2 = Point_B[6] * (fy2 - fz2); //255 30%

                        double L3 = Yn_3 > Point_A[0] ? (Point_A[3] * Math.Pow(Yn_3, (double)(1) / 3) - Point_A[2]) : (Point_A[4] * Yn_3);
                        L3 = L3 > 0 ? L3 : 0;
                        double a3 = Point_A[5] * (fx3 - fy3);
                        double b3 = Point_A[6] * (fy3 - fz3); //128 100%

                        double L4 = Yn_4 > Point_B[0] ? (Point_B[3] * Math.Pow(Yn_4, (double)(1) / 3) - Point_B[2]) : (Point_B[4] * Yn_4);
                        L4 = L4 > 0 ? L4 : 0;
                        double a4 = Point_B[5] * (fx4 - fy4);
                        double b4 = Point_B[6] * (fy4 - fz4); //128 30%

                        double D_L1 = L2 - L1;
                        double D_a1 = a2 - a1;
                        double D_b1 = b2 - b1;

                        double D_L2 = L4 - L3;
                        double D_a2 = a4 - a3;
                        double D_b2 = b4 - b3;

                        double D_E1 = Math.Pow((Math.Pow(D_L1, 2) + Math.Pow(D_a1, 2) + Math.Pow(D_b1, 2)), (double)(1) / 2);
                        double D_E2 = Math.Pow((Math.Pow(D_L2, 2) + Math.Pow(D_a2, 2) + Math.Pow(D_b2, 2)), (double)(1) / 2);

                        IRC_Delta_E_listView.Items[0].SubItems[4].Text = D_E1.ToString();
                        IRC_Delta_E_listView.Items[2].SubItems[4].Text = D_E2.ToString();
                    }
                    break;
                case "IRC_Ratio_Calu":
                    double now_lum = double.Parse(IRC_Ratio_listView.Items[0].SubItems[1].Text);
                    double last_lum = double.Parse(IRC_Ratio_listView.Items[1].SubItems[1].Text);
                    double ratio = now_lum > last_lum ? last_lum / now_lum : now_lum / last_lum;
                    IRC_Ratio_listView.Items[0].SubItems[4].Text = ratio.ToString();
                    break;
            }
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            textBox1.Text += "BF测试用" + "\r\n";
            BistSend(false, 0xbf, 0x00ff0751);    //51寄存器送07FF
        }
        public Demuraip frmdemuraip;
        bool demuraFormisopen = false;
        private void demuraToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if ((!demuraFormisopen)||(tabDemuraIP.Text != "DMRIP"))
            {
                if (frmdemuraip == null)
                {
                    frmdemuraip = new Demuraip();//给窗体变量赋值
                    frmdemuraip.TopLevel = false;
                    frmdemuraip.FormBorderStyle =FormBorderStyle.None;
                }
                frmdemuraip.Show();
                //清除之前加载的控件
                tabDemuraIP.Controls.Clear();
                //加载窗体1控件
                tabDemuraIP.Controls.Add(frmdemuraip);
                ss.SelectedIndex=ss.TabPages.IndexOf(tabDemuraIP);
                demuraFormisopen = true;
                tabDemuraIP.Text = "DMRIP";
            }       
           
          }
        
        public A_Demura frmAdemura;   //Demura bin Load
        private void labDemuraAdj_Click(object sender, EventArgs e)
        {
            if (frmAdemura == null)
            {
                frmAdemura = new A_Demura();//给窗体变量赋值
                frmAdemura.TopLevel = false;
                //frmAdemura.FormBorderStyle = FormBorderStyle.None;
            }
            frmAdemura.Show();
            //清除之前加载的控件
            tabDMURA.Controls.Clear();
            //加载窗体1控件
            tabDMURA.Controls.Add(frmAdemura);
        }
        public frmCMDX frmCMDXm;
        private void frmCMDXLoad()
        {
            {
                if (frmCMDXm == null)
                {
                    frmCMDXm = new frmCMDX();//给窗体变量赋值
                    frmCMDXm.TopLevel = false;
                    //frmCMDXm.FormBorderStyle = FormBorderStyle.None;
                }
                frmCMDXm.Show();
                //清除之前加载的控件
                tabCMDX.Controls.Clear();
                //加载窗体1控件
                tabCMDX.Controls.Add(frmCMDXm);
            }
        }
        private void frmADBLoad()
        {
            if (frmADB == null)
            {
                frmADB = new ADB_Other();//给窗体变量赋值
                frmADB.TopLevel = false;
                //frmCMDXm.FormBorderStyle = FormBorderStyle.None;
            }
            frmADB.Show();
            //清除之前加载的控件
            //tabADB.Controls.Clear();
            //加载窗体1控件
            tabADB.Controls.Add(frmADB);
        }
        private void ss_Click(object sender, EventArgs e)
        {

        }

        private void frmMain_Shown(object sender, EventArgs e)
        {
            //IC_comboBox.SelectedIndex = 90;
            //Open_Gamma_tool_Click(null, null);
            //Hide();
        }

        private byte[] Tcon_Demura_Remap_Compress_Data = new byte[1];
        private int Tcon_Demura_Remap_Data_index = 0;
        private int Tcon_Demura_Remap_Data_Total = 0;
        private int Tcon_Port_Send_Once = 3840 * 3;
        private void btn_Demura_Remap_Compress_Data_Click(object sender, EventArgs e)
        {
            Send_buf = new byte[20];
            Setting.TempRecord.cmdLen = 20 + 2;//(480 * 3 * 2)+4;
            Tcon_Demura_Remap_Compress_Data = new byte[(int)(Tcon_HACT.Value) * (int)(Tcon_VACT.Value) * 3 * 2];
            Tcon_Demura_Remap_Data_Total = (int)(Tcon_HACT.Value) * (int)(Tcon_VACT.Value) * 3 * 2;
            Tcon_Port_Send_Once = (int)(Tcon_HACT.Value) * 3;
            Tcon_Demura_Remap_Data_index = 0;

            Send_buf[0] = 0x18;
            Send_buf[1] = 0x81;
            Send_buf[2] = 0x00;
            Send_buf[3] = 0x01;
            Send_buf[4] = 0x0D;

            Send_buf[5] = (byte)(0x2c);

            Send_buf[6] = (byte)((int)(Tcon_HACT.Value) >> 8);
            Send_buf[7] = (byte)((int)(Tcon_HACT.Value) & 0xff);
            Send_buf[8] = (byte)((int)(Tcon_VACT.Value) >> 8);
            Send_buf[9] = (byte)((int)(Tcon_VACT.Value) & 0xff);


            CRCData.CalculateCrc16(Send_buf, out Send_buf[18], out Send_buf[19]);
            //CRCData.CalculateCrc16(Send_buf, out Send_buf[(480 * 3 * 2)+2], out Send_buf[(480 * 3 * 2)+3]);
            try
            {
                comPort.Write(Send_buf, 0, 20);
                // Time_Tcon.Enabled = true;
            }
            catch
            {
                show_LOG_main_msg("串口有误，请检查", "错误");
            }
        }

        private void Time_Tcon_Tick(object sender, EventArgs e)
        {
            Time_Tcon.Enabled = false;

            Send_buf = new byte[20];
            Setting.TempRecord.cmdLen = Tcon_Port_Send_Once + 4;
            Send_buf[0] = 0x18;
            Send_buf[1] = 0x81;
            Send_buf[2] = 0x00;
            Send_buf[3] = 0x01;
            Send_buf[4] = 0x0D;

            Send_buf[5] = (byte)(0x3c);
            CRCData.CalculateCrc16(Send_buf, out Send_buf[18], out Send_buf[19]);
            try
            {
                comPort.Write(Send_buf, 0, 20);
            }
            catch
            {
                show_LOG_main_msg("串口有误，请检查", "错误");
            }
        }

        private void btn_Time_Tcon_Stop_Click(object sender, EventArgs e)
        {
            Time_Tcon.Enabled = false;
        }

        private void bntDisconnectCA410_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Left)
            {
                CaSDKObj.Disconnect();    //DisconnectAll
                MessageBox.Show("CA410已断开");
            }
        }
        bool btn51loopflag = false;
        private void btn51loop_Click(object sender, EventArgs e)
        {
            btn51loopflag = !btn51loopflag;
            if (!Ca4x00calFlag) { T51.Stop(); show_LOG_main_msg("检查CAx10", "注意"); return; }
            if (btn51loopflag)
            {
                T51.Start();
            }
            else
            {
                T51.Stop();
            }
        }
        int i = 0;
        private void T51_Tick(object sender, EventArgs e)
        {
            i++;
            Generate_File_Click(Gen_DBC_control, e);
            if (i > 10)
            {
                i = 0;
                textBox1.Text += "51发送10次" + "[" + DateTime.Now.ToLongTimeString().ToString() + "]：";
                textBox1.Select(textBox1.Text.Length, 0);
                textBox1.ScrollToCaret();
            }
            T51.Interval = (int.Parse(CAS200_txt1.Text));
            btn_CAS200_Synt_Click(btn_CAS200_Measure, e);
        }

        private void btn_CAS200_Measure_KeyDown_1(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.W)
            {
                frmMain.frmain.btn_CAS200_Synt_Click(btn_CAS200_Measure, null);
            }
        }

        private int[] Value51 = new int[196] { 3501, 3590, 3680, 3771, 3860, 3950, 4021, 4093, 4166, 4237, 4308, 4380, 4453, 4524, 4595, 4665, 4736, 4809, 4879, 4950, 4998, 5046, 5093, 5140, 5184, 5228, 5273, 5317, 5361, 5405, 5450, 5495, 5539, 5583, 5627, 5672, 5715, 5759, 5802, 5846, 5890, 5934, 5977, 6021, 6064, 6109, 6152, 6196, 6240, 6284, 6328, 6371, 6415, 6458, 6503, 6546, 6590, 6633, 6677, 6722, 6765, 6809, 6852, 6897, 6940, 6984, 7027, 7071, 7111, 7150, 7189, 7228, 7268, 7307, 7346, 7385, 7424, 7464, 7503, 7542, 7581, 7620, 7660, 7699, 7738, 7777, 7817, 7856, 7895, 7934, 7973, 8013, 8052, 8091, 8130, 8169, 8209, 8248, 8276, 8304, 8332, 8360, 8388, 8416, 8444, 8472, 8500, 8528, 8556, 8583, 8612, 8640, 8668, 8695, 8724, 8752, 8780, 8807, 8835, 8864, 8892, 8919, 8947, 8976, 9004, 9031, 9059, 9087, 9115, 9143, 9170, 9198, 9225, 9253, 9281, 9309, 9336, 9364, 9392, 9419, 9447, 9474, 9503, 9530, 9558, 9585, 9613, 9641, 9669, 9696, 9724, 9752, 9780, 9808, 9837, 9865, 9894, 9922, 9950, 9978, 10006, 10035, 10063, 10092, 10120, 10149, 10177, 10205, 10233, 10261, 10290, 10319, 10347, 10375, 10404, 10432, 10460, 10488, 10515, 10544, 10572, 10599, 10627, 10656, 10684, 10713, 10741, 10769, 10798, 10826, 10854, 10882, 10910, 10939, 10967, 10995 };
        int Value51index = 1;
        private void btn51Autosend_Click(object sender, EventArgs e)
        {
            int Delay51 = Convert.ToInt16(Convert.ToByte(Gen_51h_Bits.Text)) - 1;
            tim51Send.Interval = 1;// Delay51;
            tim51Send.Start();
        }

        bool Flag_btn51sendStop = false;
        private void btn51sendStop_Click(object sender, EventArgs e)
        {
            tim51Send.Stop();
            Flag_btn51sendStop = true;
        }

        private void tim51Send_Tick(object sender, EventArgs e)
        {
            //if (Value51index < 196)
            //{
            //    int tep = Value51[Value51index];
            //    tep >>= 2;
            //    Gen_BC_lab.Text = "51";
            //    Gen_BC_lab.Text = Gen_BC_lab.Text + "," + ((tep >> 8) & 0xff).ToString("x2") + "," + ((tep >> 0) & 0xff).ToString("x2");
            //    Generate_File_Click(Gen_DBC_control, null);
            //    Value51index++;
            //}
            if (Value51index <= 3515)
            {
                Gen_BC_lab.Text = "";
                Gen_BC_lab.Text = Gen_BC_lab.Text + "" + ((Value51index >> 8) & 0xff).ToString("x2") + "," + ((Value51index >> 0) & 0xff).ToString("x2");
                Generate_File_Click(Gen_DBC_control, null);
                Value51index++;
            }
            else
                tim51Send.Stop();
        }

        private void Frm_DSC_setting_on(object sender, EventArgs e)
        {
            DSC_setting DSC_SET = new DSC_setting(this);
            DSC_SET.ShowDialog();
        }
        private void code格式转换ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (codeconvert_form == null || codeconvert_form.IsDisposed)
            {
                codeconvert_form = new Form_codeconvert(this);
                codeconvert_form.Show();
            }
            else
            {
                codeconvert_form.Activate();
            }
        }

        private void btn_IICshowExample_Click(object sender, EventArgs e)
        {
            rdoOneLineSend.Checked=true;
            txtSourcecode.Text = "// IIC Write Example:\r\n" +                
                "iicw 0x66,0 ,0x7 " + "\r\n" +
                "iicw 0x66,0xa ,0x10 " + "\r\n" +
                "iicw 0x66,0xB ,0x2d" +
                "\r\n";         

        }

        private void makeAPictureToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (Make_a_picture_form == null || Make_a_picture_form.IsDisposed)
            {
                Make_a_picture_form = new Form_Make_a_picture(this);
                Make_a_picture_form.Show();
            }
            else
            {
                Make_a_picture_form.Activate();
            }
        }
        
        private void 电源设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (PMU_setting_Form == null || PMU_setting_Form.IsDisposed)
            {
                PMU_setting_Form = new PMU_Setting(this);
                PMU_setting_Form.Show();
            }
            else
            {
                PMU_setting_Form.Activate();
            }
        }

        private void cascadeToolStripMenuItem_Click(object sender, EventArgs e)
        {            
            {
                frmRGB_Load();
                button3.Visible = false;
                tabDemuraIP.Text = "马金宝";
            }
            ss.SelectedIndex = ss.TabPages.IndexOf(tabDemuraIP);
        }

        private void flickerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (Flickerdata_form == null || Flickerdata_form.IsDisposed)
            {
                Flickerdata_form = new JEITAdata(this);
                Flickerdata_form.Show();
            }
            else
            {
                Flickerdata_form.Activate();
            }
        }

        private void Chk_bist_M_CheckedChanged(object sender, EventArgs e)
        {
            if ((!Chk_bist_M.Checked)&&(IC_comboBox.SelectedIndex== Setting.IC_Type.NT37706A))
            {
                byte[] TepArr;
                {                   
                    {
                        // BIST 模式
                        //byte[] TepArr;
                        //byte Color = 1;
                        byte GrayLevel = 1;
                        GrayLevel = byte.Parse(numPatternR.Value.ToString());
                        byte rr, gg, bb;

                        rr = GrayLevel;
                        gg = byte.Parse(numPatternG.Value.ToString());
                        bb = byte.Parse(numPatternB.Value.ToString());
                        TepArr = new byte[] {
                        1,0x11,
                        1,0x29,                       
                        2,0XEE,0X00
                       };
                    }
                }
                
                try
                {
                    comPort.Write(GetCRCArray(TepArr, 4), 0, TepArr.Length + 6);//循环部分，每段数据结尾                  
                }
                catch
                {
                    show_LOG_main_msg("串口有误，请检查", "错误");
                    return;
                }
            }
        }

        private void lIR参数设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if(m_tools_lir == null)
            {
                m_tools_lir = new Others.control_tools_lir.frm_tools_lir();
                m_tools_lir.TopLevel = false;
                m_tools_lir.FormBorderStyle = FormBorderStyle.None;
                m_tools_lir.Show();
                this.ss.SelectedTab = this.tab_page_lir;
                tab_page_lir.Controls.Add(m_tools_lir);
            }
            else
            {
                this.ss.SelectedTab = this.tab_page_lir;
            }
        }

        private void tim_show_pic_Tick(object sender, EventArgs e)
        {
            if (!this.comPort.IsOpen)
            {
                try
                {
                    comPort.PortName = Detection.GetComNum();
                    comPort.BaudRate = Setting.ComSet.comBaudRate;
                    this.openSerialPort(true);
                }
                catch
                {
                    show_LOG_main_msg("没有搜索到串口！", "错误提示");
                    showmsg("停止循环切图");
                    tim_show_pic.Enabled = false;
                }
            }
            if (listBox3_BMPFile.SelectedIndex < listBox3_BMPFile.Items.Count - 1)
            {
                listBox3_BMPFile.SelectedIndex++;
            }
            else
            {
                listBox3_BMPFile.SelectedIndex = 0;
            }
            btnPrevPic_Click(null, null);
        }

        private void LIR_RCH_SHOW_Click(object sender, EventArgs e)
        {
            LIR_RCH LIR_RCH_SHOW = new LIR_RCH(this);
            LIR_RCH_SHOW.Show();
        }

        private void UDP_RCH_SHOW_Click_1(object sender, EventArgs e)
        {
            UDP_RCH UDP_RCH_SHOW = new UDP_RCH(this);
            UDP_RCH_SHOW.Show();
        }

    }
}

